渲染通过通过道具

时间:2020-03-13 18:00:58

标签: javascript html reactjs frontend react-habitat

我目前在一个项目上使用React栖地,并且通过以下方式渲染组件

<div data-component="MyComponent" data-prop-titl="My title"></div>

我遇到了一个问题,我试图通过富文本编辑器传递一些标记,该文本包含上面的示例所示的标记。

我希望能够使用内部的react-habitat组件引用来呈现富文本。

因此,以上参考基本上可以与富文本一起传递,并且仍然可以作为React组件呈现。

这可能吗?

2 个答案:

答案 0 :(得分:0)

可能类似的东西可能会帮助

function createMarkup() {
  return {__html: '<div data-component="MyComponent" data-prop-titl="My title"></div>'};
}

function MyComponent() {
  return <div dangerouslySetInnerHTML={createMarkup()} />;
}

但这是一个非常冒险的做法,可能会使您的用户遭受跨站点脚本(XSS)攻击

答案 1 :(得分:0)

我是React Habitat的原始作者。

您将遇到将HTML放入属性字符串的问题。其same problem with JSON

我只需将HTML放入栖息地组件中,然后使用the proxy variable the React Habitat sets for you

例如

 <div data-component="MyWysiwygViewer">
     <h2>Some HTML text</h2>
     <p>With some body</p> 
 </div>

在组件中,我将获得以下数据:

 constructor(props) {
      super(props);

      const html = props.proxy.innerHTML;
 }

或者

您可以将其放在隐藏的div中

 <div id="myHtml" style="display: none" >
     <h2>Some HTML text</h2>
     <p>With some body</p> 
 </div>

 <div data-component="MyWysiwygViewer" data-prop-html-id="myHtml" />

然后在组件中,我将获得以下数据:

 constructor(props) {
      super(props);

      const html = document.getElementById(props.htmlId).innerHTML;
 }