我正在尝试从外部源接收一段 HTML 标记,并在渲染之前将 React 组件注入(inject)其中的特定部分。

为了实现这一目标,我一直在使用 react-html-parser ( https://github.com/wrakky/react-html-parser )

我有这个例子工作......虽然,它感觉很hacky并且不可能是实现这一点的最佳方法。

// 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" />); 

另一个例子,设置稍微复杂一些;

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: 
        } 
    } 
}); 

在此示例中,我希望将 src 添加到图像元素,并将标题添加到Figcaption。 标记的其余部分需要保持不变,但应进行相应渲染。 只是为了澄清一下,我已经准备了Reactify属性的逻辑,例如class 变为 className

我知道react-html-parser有一种自定义的方式来转换节点。但这迫使我在代码中定义结果应该是什么样子。我从外部源收到的 HTML 是动态的,例如包装 imagediv 元素(及其属性)可能会有所不同。

感觉有点失落。实现这一目标的最佳方法是什么?

请您参考如下方法:

您可以使用 ReactDOMServer 将 React 元素注入(inject) HTML 标记(ReactDOMServer.renderToString 在浏览器中也可用)。逐步算法将是:

1) 将 React 元素渲染为字符串

2) 创建一个 template 元素并将加载的 HTML 粘贴到其 innerHTML 属性中(您需要 template 因为您想注入(inject) React HTML 渲染之前)

3) 将 React 组件的 HTML 注入(inject)到 template 内的特定元素

4) 在页面上渲染模板内容

5) 如果需要的话,水合React组件

在 StackBlitz 上查看此演示 https://stackblitz.com/edit/react-yvncqj


评论关闭
IT虾米网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!