我从AJAX请求中得到一个HTML字符串,看起来如下所示:
<div> <SpecialComponent/> <SecondSpecialComponent/></div>我需要的是能够在React组件中使用这个字符串,因为它是有效的JSX。
我试着按照本讨论中的指示使用dangerouslySetInnerHTML:how-to-parse-html-to-react-component
我也尝试过像react-html-parse和html-react-parser这样的反应库。未获成功
当我使用AngularJS(1)时,我使用了一些小指令来处理这种情况。我需要用反应来达到同样的目的。有什么想法吗?
编辑:如果有人感兴趣,我找到了一个处理这个问题的库:https://www.npmjs.com/package/react-jsx-parser
发布于 2018-03-21 15:42:48
你不应该这样做的。虽然在使用JSX时,React组件看起来像html标记,但它们实际上要么是类,要么是函数。您所要做的就相当于尝试解析:
"<div>document.write('foo')</div>"您实际上是将字符串形式的javascript函数名与同一字符串中的html标记混合。您必须解析该字符串以将React组件从周围的html标记中分离出来,将字符串形式的React组件映射到实际的React对应项,并使用ReactDOM.render将该组件添加到页面中。
let mapping = [
{"name":"<SpecialComponent/><SecondSpecialComponent/>","component":<SpecialComponent/><SecondSpecialComponent/>},
{"name":"<someOtherComponent/><someOtherComponent/>","component":<someOtherComponent/><someOtherComponent/>}
];
let markup = "<div><SpecialComponent/><SecondSpecialComponent/></div>";
let targetComponent;
mapping.forEach((obj) => {if(markup.indexOf(obj.name)>-1){
targetComponent=obj.component;//acquired a reference to the actual component
markup.replace(obj.name,"");//remove the component markup from the string
}
});
/*place the empty div at the target location within the page
give it an "id" attribute either using element.setAttribute("id","label") or
by just modifying the string to add id="label" before the div is placed in
the DOM ie, <div id='label'></div>*/
//finally add the component using the id assigned to it
ReactDOM.render(targetComponent,document.getElementById("label"));以前从没试过这个。我想知道这是否真的有效:)
发布于 2018-03-21 14:39:12
我的建议是你做如下事情。
首先,将状态变量设置为等于要返回的HTML。
this.setState({html: response.data.html})然后在您返回时,您可以执行以下操作
return (
{this.state.html}
);https://stackoverflow.com/questions/49408979
复制相似问题