React.js将HTML字符串转换为JSX

问题描述:

我在处理Facebook的ReactJS时遇到问题。每当我执行ajax并想要显示html数据时,ReactJS会将其显示为文本。 (请参见下图)

I'm having trouble dealing with facebook's ReactJS. Whenever I do ajax and want to display an html data, ReactJS displays it as text. (See figure below)

数据通过jquery Ajax的成功回调函数显示。

The data is displayed through the success callback function of the jquery Ajax.

$.ajax({
   url: url here,
   dataType: "json",
   success: function(data) {
      this.setState({
           action: data.action
      })
   }.bind(this)
});

有没有简单的方法可以将其转换为html?

Is there any easy way to convert this into html? How should I do it using ReactJS?

默认情况下,React会转义HTML以防止 XSS(跨站脚本)。如果您确实要呈现HTML,则可以使用 dangerouslySetInnerHTML 属性:

By default, React escapes the HTML to prevent XSS (Cross-site scripting). If you really want to render HTML, you can use the dangerouslySetInnerHTML property:

<td dangerouslySetInnerHTML={{__html: this.state.actions}} />

React强制使用这种故意繁琐的语法,这样您就不会意外地将文本呈现为HTML并引入XSS错误。

React forces this intentionally-cumbersome syntax so that you don't accidentally render text as HTML and introduce XSS bugs.