我在处理facebook的ReactJS时遇到了麻烦。每当我使用ajax并想要显示html数据时,ReactJS将其显示为文本。(见下图)

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

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

有没有什么简单的方法把它转换成html?我应该如何使用ReactJS?


当前回答

这可以通过使用块{[]}中的内容来解决。为了更清楚,可以参考下面的示例。

{[
   'abc',
   <b>my bold</b>, 
   'some other text'
]} 

这将保留标签下文本的格式,而其他文本将作为纯文本打印。

其他回答

我发现了这把js小提琴。它是这样工作的

function unescapeHTML(html) {
    var escapeEl = document.createElement('textarea');
    escapeEl.innerHTML = html;
    return escapeEl.textContent;
}

<textarea className="form-control redactor"
                          rows="5" cols="9"
                          defaultValue={unescapeHTML(this.props.destination.description)}
                          name='description'></textarea>

JSFIDDLE 链接

现在有更安全的方法来实现这一点。文档已经更新了这些方法。

其他方法

Easiest - Use Unicode, save the file as UTF-8 and set the charset to UTF-8. <div>{'First · Second'}</div> Safer - Use the Unicode number for the entity inside a Javascript string. <div>{'First \u00b7 Second'}</div> or <div>{'First ' + String.fromCharCode(183) + ' Second'}</div> Or a mixed array with strings and JSX elements. <div>{['First ', <span>&middot;</span>, ' Second']}</div> Last Resort - Insert raw HTML using dangerouslySetInnerHTML. <div dangerouslySetInnerHTML={{__html: 'First &middot; Second'}} />

你也可以从html-react-parser中使用Parser()。 我也用过。连接共享。

如果你提前知道你想呈现的字符串中有哪些标签;例如,如果在创建字符串时只允许某些标记;解决这个问题的一个可能的方法是使用Trans实用程序:

import { Trans } from 'react-i18next'
import React, { FunctionComponent } from "react";

export type MyComponentProps = {
    htmlString: string
}

export const MyComponent: FunctionComponent<MyComponentProps> = ({
  htmlString
}) => {
  return (
    <div>
      <Trans
        components={{
          b: <b />,
          p: <p />
        }}
      >
        {htmlString}
      </Trans>
    </div>
  )
}

然后你就可以一如既往地使用它了

<MyComponent
    htmlString={'<p>Hello <b>World</b></p>'}
/>

对于那些还在尝试的人,npm安装react-html-parser

当我安装它时,它的周下载量是123628次。

import ReactHtmlParser from 'react-html-parser'

<div>{ReactHtmlParser(htmlString)}</div>