什么时候在在react中使用dangerouslySetInnerHTML

介绍:

由于 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

element with the data coming from a rich text editor. Imagine you have a webpage where people can submit comments and you allow them to use a rich text editor. In this case, the output of that rich text editor is likely to be HTML with tags such as

, , 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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值