介绍:
由于 React 使用独立于浏览器的系统来操作 DOM 元素,从而防止与 DOM 直接交互。这将使得在所见即所得编辑器中创建的富文本渲染 HTML标签是很困难的。 我们可以使用 dangerouslySetInnerHTML解决
dangerouslySetInnerHTML is a property that you can use on HTML elements in a React application to programmatically set their content. Instead of using a selector to grab the HTML element, then setting its innerHTML, you can use this property directly on the element.
When dangerouslySetInnerHTML is used, React also knows that the content of that specific element is dynamic, and, for the children of that node, it simply skips the comparison against the virtual DOM to gain some extra performance.
As the name of the property suggests, it can be dangerous to use because it makes your code vulnerable to cross-site scripting (XSS) attacks. This becomes an issue especially if you are fetching data from a third-party source or rendering content submitted by users.
When to use dangerouslySetInnerHTML
A use case where you need to set the HTML content of a DOM element is when you populate a
, , and .
Consider the following code snippet, which would render the string without being aware of the tag in it — meaning that the output would be just the string itself without any bold text, like so: lorem ipsum.
参考文档:
https://blog.logrocket.com/using-dangerouslysetinnerhtml-in-a-react-application/
https://zhuanlan.zhihu.com/p/257970879