react 中渲染html
I had this problem - I needed to add an HTML string in a React application, coming from a WYSIWYG editor, but simply adding {myString}
to the JSX was escaping the HTML.. so the HTML tags were displayed to the user!
我遇到了这个问题-我需要在WYSIWYG编辑器中的React应用程序中添加HTML字符串,但是将{myString}
添加到JSX就是将HTML转义。.因此,向用户显示了HTML标签!
How did I solve it? I saw 2 solutions, basically. The first native, the second required a library.
我该如何解决? 我基本上看到了2个解决方案。 第一个本机,第二个本机需要一个库。
第一个解决方案: dangerouslySetInnerHTML
使用dangerouslySetInnerHTML
(First solution: use dangerouslySetInnerHTML
)
You can use the dangerouslySetInnerHTML
attribute on an HTML element to add an HTML string inside its content:
您可以在HTML元素上使用dangerouslySetInnerHTML
属性在其内容内添加HTML字符串:
<div
dangerouslySetInnerHTML={{
__html:
}}></div>
Remember that it’s called dangerously for a reason. HTML is not escaped at all in this case, and it might cause XSS issues.
请记住,它被称为危险是有原因的。 在这种情况下,HTML根本不会转义,这可能会导致XSS问题。
But there are good use cases for this.
但是有很好的用例。
第二种解决方案:使用第三方库 (Second solution: use a 3rd party library)
There are many libraries that implement the functionality that dangerouslySetInnerHTML
provides, in a simpler way.
有许多库以更简单的方式实现了dangerouslySetInnerHTML
提供的功能。
One of them is the react-html-parser
library.
其中之一是react-html-parser
库。
See the library on GitHub: /wrakky/react-html-parser
参见GitHub上的库: https : ///wrakky/react-html-parser
Warning: at the time of writing, it’s not been updated in the last 2 years, so things might break in the future. It worked for me.
警告:在撰写本文时,它在过去两年中尚未更新,因此将来可能会中断。 它为我工作。
使用哪一个? (Which one to use?)
You can look for other similar libraries, but in the end I chose to use the dangerouslySetInnerHTML
way.
您可以寻找其他类似的库,但最后我选择使用dangerouslySetInnerHTML
方式。
This dangerously-looking name was a built-in reminder to pay attention at correctly whitelisting the HTML tags I allowed the user to enter to that HTML string.
这个看起来很危险的名称是一个内置的提醒,请注意正确将我允许用户输入该HTML字符串HTML标签列入白名单。
翻译自: /how-to-render-html-react/
react 中渲染html