将任何随机html对象转换为react js中的字符串

时间:2017-04-24 12:40:48

标签: javascript html reactjs

我想在 React 中渲染一个html对象。我需要使用html,将其作为String传递给 React 并将其渲染到那里。我不确定如何继续。

html对象可以是

之类的东西
<p>Hey man&nbsp;</p>
<p>nlkansnsa</p>
<p>as</p>
<p><strong>asasas</strong></p>
<p><strong>knla</strong></p>
<p><br></p>
<ul>
  <li><strong>point 1&nbsp;</strong></li>
  <li><strong>point 2</strong></li>
  <li><strong>point 3&nbsp;</strong></li>
</ul>
<p><br></p>

1 个答案:

答案 0 :(得分:1)

使用包含dangerouslySetInnerHTML元素的renderhtml字符串,如下所示:

<div dangerouslySetInnerHTML={{ __html: "<div>hello</div>" }}></div>

您也可以传递包含该字符串的任何变量,如下所示:

let htmlString = "<div>hello</div>";

<div dangerouslySetInnerHTML={{ __html:  htmlString}}></div>

检查 DOC

检查此示例:

&#13;
&#13;
let string = "<p>Hey man&nbsp;</p><p>nlkansnsa</p><p>as</p><p><strong>asasas</strong></p><p><strong>knla</strong></p><p><br></p><ul><li><strong>point 1&nbsp;</strong></li><li><strong>point 2</strong></li><li><strong>point 3&nbsp;</strong></li></ul><p><br></p>";

var App = () => {

   return(
      <div>
         <div dangerouslySetInnerHTML={{ __html: "<div>hello</div>" }}></div>
         <div dangerouslySetInnerHTML={{ __html: string }}></div>
      </div>
   )

}

ReactDOM.render(<App/>, document.getElementById('app'))
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id='app'/>
&#13;
&#13;
&#13;