我在处理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?
我推荐使用milesj创建的Interweave。它是一个非凡的库,使用了许多巧妙的技术来解析HTML并安全地将其插入DOM。
Interweave是一个react库,可以安全地渲染HTML,过滤
属性,自动抓取文本与匹配器,渲染表情符号字符,和
更多。
Interweave是一个健壮的React库,可以:
安全地渲染HTML而不使用dangerlysetinnerhtml。
安全地剥离HTML标记。
自动XSS和注射保护。
使用过滤器清洁HTML属性。
使用匹配器插入组件。
自动链接url, ip,电子邮件和标签。
渲染表情符号和表情符号字符。
还有更多!
使用的例子:
import React from 'react';
import { Markup } from 'interweave';
const articleContent = "<p><b>Lorem ipsum dolor laboriosam.</b> </p><p>Facere debitis impedit doloremque eveniet eligendi reiciendis <u>ratione obcaecati repellendus</u> culpa? Blanditiis enim cum tenetur non rem, atque, earum quis, reprehenderit accusantium iure quas beatae.</p><p>Lorem ipsum dolor sit amet <a href='#testLink'>this is a link, click me</a> Sunt ducimus corrupti? Eveniet velit numquam deleniti, delectus <ol><li>reiciendis ratione obcaecati</li><li>repellendus culpa? Blanditiis enim</li><li>cum tenetur non rem, atque, earum quis,</li></ol>reprehenderit accusantium iure quas beatae.</p>"
<Markup content={articleContent} /> // this will take the articleContent string and convert it to HTML markup. See: https://milesj.gitbook.io/interweave
//to install package using npm, execute the command
npm install interweave
现有答案中缺少的一个选项是使用<React。片段>(在React v16及更高版本中可用)。我认为这是最好的,因为它允许您将任何html元素存储为JSX变量,并在以后引用它。也因为使用dangerlysetinnerhtml是不安全的。
例如
const App = () => {
const Windows = <React。Fragment>Microsoft <abbr title="Operating System">OS</abbr></React. bat。片段>
回报(
< ul >
<李> {Windows} < /李>
< / ul >
);
};
ReactDOM。render(<App />, document.getElementById("root"));
< script src = " https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js " > < /脚本>
< script src = " https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js " > < /脚本>
< div id = "根" > < / div >
其他选择和考虑:
If you're fetching the HTML from external sources, then you cannot use this approach because the fetched HTML will be in a string format. In that case you need to parse the HTML using a HTML Parser like html-react-parser
If you don't have any keys or attributes, you can also use <></> which is a shorthand for <React.Fragment></React.Fragment>
Keep in mind that dangerouslySetInnerHTML is dangerous to use because malicious client side code can be injected via script tags:
@Brett has also suggested other alternatives:
Note: using quotes in a JSX Variale
You should not surround a JSX variable with quotes (like a regular variable) - you should surround it with <React.Fragment> </ React.Fragment>
you should not escape quotes in a html tag of a JSX variable - for example the title in <abbr /> tag above has quotes which are not escaped.