在状态字符串中呈现 html [英] render html in state string

查看:32
本文介绍了在状态字符串中呈现 html的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 setState 来更新 html 的一部分,但我发现没有呈现新的更新 html.这是代码,js fiddle:

html:

hello
world

<div id='内容'></div>

js:

var Main = React.createClass({getInitialState:函数(){返回{输出:'你好<br/>世界<br/>'};},渲染:函数(){返回 (<div>{this.state.output}

);}});React.renderComponent(

, document.getElementById('content'));

我省略了从服务器更新 html 的部分,但结果是一样的.如何让处于状态的字符串被渲染?

解决方案

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

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

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

用于执行此操作的 API 故意复杂,因为常规执行此操作并不安全.React 具有针对 XSS 的保护措施,使用 dangerouslySetInnerHTML 可以绕过这些保护措施,如果您不清理该数据,则将面临风险.

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'));

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?

解决方案

Use dangerouslySetInnerHTML to inject HTML as a string in React (but note that React won’t be able to use this markup in its virtual DOM):

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

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

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆