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

Dee*_*Jha 2 react-native-render-html

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

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

<a> <b> <c meta="xyz"> Some text </c> <b> </a>
Run Code Online (Sandbox Code Playgroud)

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

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

Jul*_*lph 5

该 API 最初并不是为处理此类用例而设计的,但对于 5.0.0 版本来说,这非常简单!

\n

版本 6.x

\n
import * as React from \'react\';\nimport HTML, {domNodeToHTMLString} from \'react-native-render-html\';\n\nfunction CustomRenderer({ tnode, style, key }) {\n  const html = React.useMemo(() => domNodeToHTMLString(tnode.domNode), [tnode]);\n  return <Custom key={key} html={html} style={style} />;\n}\n
Run Code Online (Sandbox Code Playgroud)\n

版本 5.x

\n

从版本 5 开始,在新 util 的帮助下变得非常容易domNodeToHTMLString,请参见下面的代码片段:

\n
import * as React from \'react\';\nimport HTML, {domNodeToHTMLString} from \'react-native-render-html\';\n\nfunction customRenderer(htmlAttribs, children, inlineStyle, passProps) {\n  const html = domNodeToHTMLString(passProps.domNode);\n  return <Custom key={passProp.key} html={html} />;\n}\n
Run Code Online (Sandbox Code Playgroud)\n

4.x及以下版本

\n

要使用此技巧,您需要将 \xe2\x80\x9cstringify-entities\xe2\x80\x9d 添加到依赖项列表中。这个 hack 的主要作用是使用钩子向 DOM 节点alterNode添加一个非常规的属性。__rawHtml此后该属性将被传递给渲染器函数。

\n
import * as React from \'react\';\nimport HTML from \'react-native-render-html\';\nimport strigifyEntities from \'stringify-entities\';\nimport Custom from \'./Custom\';\n\nfunction renderOpeningTag(tag, attributes) {\n  const strAttributes = [];\n  Object.keys(attributes).forEach((key) => {\n    strAttributes.push(`${key}="${strigifyEntities(`${attributes[key]}`)}"`);\n  });\n  return `<${tag}${strAttributes.length ? \' \' : \'\'}${strAttributes.join(\' \')}>`;\n}\n\nfunction nodeToRawHTML(root) {\n  let html = \'\';\n  if (root.type === \'tag\') {\n    const strChildren = root.children.reduce((prev, curr) => {\n      return `${prev}${nodeToRawHTML(curr)}`;\n    }, \'\');\n    html = `${renderOpeningTag(root.name, root.attribs)}${strChildren}</${\n      root.name\n    }>`;\n  } else if (root.type === \'text\') {\n    const text = strigifyEntities(root.data);\n    html = text;\n  }\n  return html;\n}\n\nfunction alterNode(node) {\n  if (node.type === \'tag\' && node.name === \'c\') {\n    node.attribs.__rawHtml = nodeToRawHTML(node);\n  }\n}\n\nconst renderers = {\n  c: ({__rawHtml}, children, convertedCSSStyles, passProp) => {\n    return <Custom key={passProp.key} html={__rawHtml} />\n  },\n};\n\nexport default function App() {\n  return (\n    <HTML\n      renderers={renderers}\n      alterNode={alterNode}\n      html={\'<a> <b> <c meta="xyz"> Some text </c> <b> </a>\'}\n    />\n  );\n}\n
Run Code Online (Sandbox Code Playgroud)\n