我正在使用react-native- render -html来呈现html。renderers
方法允许我提供自定义函数来呈现特定的标记。但是,我希望使用来自源代码的原始内部HTML,将子组件替换为我的自定义组件。
考虑一下。我将以下html代码片段提供给<HTML />
组件:
<a> <b> <c meta="xyz"> Some text </c> <b> </a>
我有一个自定义的渲染器,它返回一个组件,该组件接受一个html字符串,并对其进行一些魔法处理:
const renderers = {
c: () => (
<Custom html={/** how do I get "<c meta="xyz"> Some text </c>"? */} />
)
}
发布于 2020-09-20 22:28:12
API最初并不是为处理这类用例而设计的,但是对于版本5.0.0来说,它非常简单!
版本6.x
import * as React from 'react';
import HTML, {domNodeToHTMLString} from 'react-native-render-html';
function CustomRenderer({ tnode, style, key }) {
const html = React.useMemo(() => domNodeToHTMLString(tnode.domNode), [tnode]);
return <Custom key={key} html={html} style={style} />;
}
版本5.x
从版本5开始,在新的domNodeToHTMLString
util的帮助下,它变得非常简单,请参阅以下代码片段:
import * as React from 'react';
import HTML, {domNodeToHTMLString} from 'react-native-render-html';
function customRenderer(htmlAttribs, children, inlineStyle, passProps) {
const html = domNodeToHTMLString(passProps.domNode);
return <Custom key={passProp.key} html={html} />;
}
4.x及更低版本
要使用这个技巧,你需要将“stringify-entities”添加到你的依赖列表中。这个技巧基本上是使用alterNode
钩子向DOM节点添加一个非常非常规的__rawHtml
属性。之后,该属性将被传递给渲染器函数。
import * as React from 'react';
import HTML from 'react-native-render-html';
import strigifyEntities from 'stringify-entities';
import Custom from './Custom';
function renderOpeningTag(tag, attributes) {
const strAttributes = [];
Object.keys(attributes).forEach((key) => {
strAttributes.push(`${key}="${strigifyEntities(`${attributes[key]}`)}"`);
});
return `<${tag}${strAttributes.length ? ' ' : ''}${strAttributes.join(' ')}>`;
}
function nodeToRawHTML(root) {
let html = '';
if (root.type === 'tag') {
const strChildren = root.children.reduce((prev, curr) => {
return `${prev}${nodeToRawHTML(curr)}`;
}, '');
html = `${renderOpeningTag(root.name, root.attribs)}${strChildren}</${
root.name
}>`;
} else if (root.type === 'text') {
const text = strigifyEntities(root.data);
html = text;
}
return html;
}
function alterNode(node) {
if (node.type === 'tag' && node.name === 'c') {
node.attribs.__rawHtml = nodeToRawHTML(node);
}
}
const renderers = {
c: ({__rawHtml}, children, convertedCSSStyles, passProp) => {
return <Custom key={passProp.key} html={__rawHtml} />
},
};
export default function App() {
return (
<HTML
renderers={renderers}
alterNode={alterNode}
html={'<a> <b> <c meta="xyz"> Some text </c> <b> </a>'}
/>
);
}
https://stackoverflow.com/questions/63979897
复制相似问题