【问题标题】:Rendering react habitat components through HTML thats passed through a prop通过通过道具传递的 HTML 渲染反应栖息地组件
【发布时间】:2020-06-25 18:04:19
【问题描述】:

我目前正在一个项目中使用 Reacthabitat,并且我通过如下方式渲染组件

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

我遇到了一个问题,我试图从包含上述示例的标记的富文本编辑器中传递一些标记。

我希望能够使用里面的 react-habitat 组件引用来渲染富文本。

所以上面的引用基本上可以通过富文本传递,仍然可以作为一个react组件渲染出来。

这可能吗?

【问题讨论】:

    标签: javascript html reactjs frontend react-habitat


    【解决方案1】:

    这样的事情可能会有所帮助

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

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

    【讨论】:

    • 对不起,伙计,这不是我的意思——我知道如何传递 HTML,但我想用 HTML 传递 react-habitat 引用,它会用 props 加载到正确的 react 组件中跨度>
    【解决方案2】:

    我是 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;
     }
    

    【讨论】:

      猜你喜欢
      • 2021-05-18
      • 2020-08-18
      • 1970-01-01
      • 1970-01-01
      • 2020-12-14
      • 2018-12-19
      • 2023-03-09
      • 2023-01-18
      • 2019-02-14
      相关资源
      最近更新 更多