React.js:设置innerHTML 与危险的SetInnerHTML [英] React.js: Set innerHTML vs dangerouslySetInnerHTML

查看:32
本文介绍了React.js:设置innerHTML 与危险的SetInnerHTML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

设置元素的innerHTML 与在元素上设置危险的SetInnerHTML 属性有什么幕后"区别吗?假设为了简单起见,我正在对事物进行适当的消毒.

Is there any "behind the scenes" difference from setting an element's innerHTML vs setting the dangerouslySetInnerHTML property on an element? Assume I'm properly sanitizing things for the sake of simplicity.

示例:

var test = React.createClass({
  render: function(){
    return (
      <div contentEditable='true' dangerouslySetInnerHTML={{ __html: "Hello" }}></div>
    );
  }
});

对比

var test = React.createClass({
  componentDidUpdate: function(prevProp, prevState){
    this.refs.test.innerHTML = "Hello";
  },
  render: function(){
    return (
      <div contentEditable='true' ref='test'></div>
    );
  }
});

我正在做的事情比上面的例子复杂一些,但总体思路是一样的

I'm doing something a bit more complicated than the above example, but the overall idea is the same

推荐答案

是的,有区别!

使用 innerHTMLdangerouslySetInnerHTML 的直接效果是相同的——DOM 节点会随着注入的 HTML 更新.

The immediate effect of using innerHTML versus dangerouslySetInnerHTML is identical -- the DOM node will update with the injected HTML.

然而,在幕后,当你使用 dangerouslySetInnerHTML 时,它让 React 知道该组件内部的 HTML 不是它关心的.

However, behind the scenes when you use dangerouslySetInnerHTML it lets React know that the HTML inside of that component is not something it cares about.

因为 React 使用虚拟 DOM,当它比较 diff 与实际 DOM 时,它可以直接绕过检查该节点的子节点因为它知道 HTML 来自另一个来源.因此,性能有所提升.

Because React uses a virtual DOM, when it goes to compare the diff against the actual DOM, it can straight up bypass checking the children of that node because it knows the HTML is coming from another source. So there's performance gains.

更重要的是,如果只是简单地使用innerHTML,React是无法知道DOM节点被修改的.下次调用 render 函数时,React 将覆盖手动注入的内容,并使用它认为该 DOM 节点的正确状态应该是什么.

More importantly, if you simply use innerHTML, React has no way to know the DOM node has been modified. The next time the render function is called, React will overwrite the content that was manually injected with what it thinks the correct state of that DOM node should be.

您使用 componentDidUpdate 始终确保内容同步的解决方案我认为可行,但在每次渲染期间可能会出现闪光.

Your solution to use componentDidUpdate to always ensure the content is in sync I believe would work but there might be a flash during each render.

这篇关于React.js:设置innerHTML 与危险的SetInnerHTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆