我试图从外部来源接收一段HTML标记,并将React组件注入到它的特定部分中,然后再进行渲染。
为此,我一直在使用react-html-parser(https://github.com/wrakky/react-html-parser)
我有这个示例在工作……尽管如此,但它感觉很笨拙,不可能实现这一目标的最佳方法。
// a simple component
const Image = props => {
return <img {...props}/>
};
// this resource comes from an external source and can differ
// ultimately, I would like to be able to target certain elements selecting their data-attributes
// to insert a React component
const externalHTML = '<div class="image"></div>';
// using the react-html-parser library to convert the externalHTML into a React component
const DynamicReactComponent = ReactHtmlParser(externalHTML);
// manually injecting a React component into the dynamically created component
DynamicReactComponent.props.children.push(<Image src="something/anything.jpg" />);
Run Code Online (Sandbox Code Playgroud)
另一个例子,设置有点复杂。
const externalHTML = '
<div class="someClass">
<figure class="image">
<img src=""/>
<figcaption></figcaption>
</figure>
</div>';
// using the react-html-parser library to convert the externalHTML into a React component
const DynamicReactComponent = ReactHtmlParser(externalHTML);
// way too hacky....
// and it does not fully work
DynamicReactComponent.props.children.map(child => {
if(typeof child === 'object' && 'type' in child) {
switch(child.type) {
case 'img':
// this cannot be done as it's readonly
child.props.src = 'something/anything.jpg';
break;
case 'figcaption':
return child.props.children.push(<Text/>)
default:
}
}
});
Run Code Online (Sandbox Code Playgroud)
在此示例中,我希望为图像元素添加一个src,为figcaption添加一个标题。标记的其余部分需要保持不变,但应进行相应渲染。为了澄清起见,我已经 准备了逻辑来实现Reactify属性,例如class
变为className
。
我知道react-html-parser有一种自定义方式来转换节点。但这迫使我在代码中定义结果的外观。我从外部来源收到的HTML是动态的,div
包装元素的元素(及其属性)的数量image
可能有所不同。
我有点失落。实现此目标的最佳方法是什么?
您可以使用ReactDOMServer
将 React 元素注入 HTML 标记(ReactDOMServer.renderToString
在浏览器中也可用)。逐步算法将是:
1) 将 React 元素渲染为字符串
2)创建一个template
元素并将加载的 HTML 粘贴到其innerHTML
属性中(您需要template
,因为您想在渲染 HTML之前注入 React)
3)将React组件的HTML注入到内部的特定元素中template
template
4)在页面上渲染内容
5) 如果需要,水合反应组分
在 StackBlitz 上查看此演示 https://stackblitz.com/edit/react-yvncqj
归档时间: |
|
查看次数: |
413 次 |
最近记录: |