在 react-native-render-html 自定义渲染器中提取原始 HTML

Extract raw HTML in react-native-render-html custom renderer

我正在使用 react-native-render-html 来渲染 html。 renderers 方法允许我提供自定义函数来呈现特定标签。但是我想用我的自定义组件替换子组件,使用源代码中的原始内部 HTML。

考虑一下。我向 <HTML /> 组件提供了以下 html 片段:

<a> <b> <c meta="xyz"> Some text </c> <b> </a>

我有一个自定义渲染器,它 returns 一个接受 html 字符串并用它做一些魔术的组件:

const renderers = {
  c: () => (
    <Custom html={/** how do I get "<c meta="xyz"> Some text </c>"? */} />
  )
}

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 实用程序的帮助下变得非常容易,请参见下面的代码片段:

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 所做的基本上是使用 alterNode 挂钩将非常非常规的 __rawHtml 属性添加到 DOM 节点。该属性随后将传递给渲染器函数。

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>'}
    />
  );
}