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 开始,在新 util 的帮助下非常容易domNodeToHTMLString
,请参见下面的代码段:
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 及以下
要使用此 hack,您需要将“stringify-entities”添加到依赖项列表中。这个 hack 基本上是用钩子给DOM 节点alterNode
添加一个非常规的属性。__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>'}
/>
);
}