呈现状态字符串中的html

render html in state string

本文关键字:html 字符串 状态      更新时间:2023-09-26

我使用setState更新部分html,但我发现新的更新html没有呈现。这是代码,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的部分,但结果是一样的。如何让处于状态的字符串被呈现?

使用dangerouslySetInnerHTML将HTML作为字符串注入React(但请注意,React将无法在其虚拟DOM中使用此标记):

<div dangerouslySetInnerHTML={{__html: this.state.output}} />

http://jsfiddle.net/5Y8r4/11/

做这件事的API是故意复杂的,因为这不是安全的常规做法。React有针对XSS的保护措施,使用dangerouslySetInnerHTML可以绕过这些保护措施,如果你不清理这些数据,就会让你面临风险。