在状态字符串中呈现html [英] render html in state string
问题描述
我使用setState更新html的一部分,但是我发现新的更新html没有呈现。这是代码, js小提琴:
I use setState to update part of the html but I found the new update html is not rendered. Here is the code, js fiddle:
html:
<div>hello<br />world<br /></div>
<div id='content'></div>
js:
var Main = React.createClass({
getInitialState: function() {
return {output: 'hello<br />world<br />'};
},
render: function() {
return (
<div>
{this.state.output}
</div>
);
}
});
React.renderComponent(<Main/>, document.getElementById('content'));
我省略了从服务器更新html的部分,但结果相同。如何让字符串处于状态被渲染?
I omit the part that update html from the server but the result is the same. How to let the string in state be rendered?
推荐答案
使用 dangerouslySetInnerHTML
在React中注入HTML作为字符串React将无法在其虚拟DOM中使用此标记):
Use dangerouslySetInnerHTML
to inject HTML as a string in React (but note that React won’t be able to use this markup in it’s virtual DOM):
<div dangerouslySetInnerHTML={{__html: this.state.output}} />
执行此操作的API是故意复杂的,因为这样做不安全常规。 React具有对XSS的保护,使用 dangerouslySetInnerHTML
可避免这些情况,并且如果您没有清理这些数据,就会面临风险。
The API for doing this is deliberately complex because this isn't safe to do routinely. React has protections against XSS, using dangerouslySetInnerHTML
circumvents those and opens you up to risk if you aren't sanitizing that data.
这篇关于在状态字符串中呈现html的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!