React.js:设置innerHTML vs dangerouslySetInnerHTML [英] React.js: Set innerHTML vs dangerouslySetInnerHTML

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

问题描述

设置元素的innerHTML与设置元素上危险的SetInnerHTML属性有什么区别吗?为了简单起见,假设我正确地清理了东西。



示例:

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

vs

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

我做的事情比上面的例子复杂一点,但总体思路是一致的

解决方案

是的,有区别!

使用 innerHTML dangerouslySetInnerHTML 的直接影响是相同的 - DOM节点将使用注入HTML。



然而,幕后使用危险的设置HTML 它让React知道该组件内的HTML不是它关心的东西。



因为React使用虚拟DOM,所以当它比较diff与实际DOM时,它可以直接绕过检查该节点的子节点,因为它知道HTML来自其他源。因此,性能将得到提升。

更重要的是,如果您只是简单地使用 innerHTML ,那么React没有办法知道DOM节点已被修改。下一次调用 render 函数时, React将覆盖手动注入的内容,它认为该DOM节点的正确状态应该be。



您使用 componentDidUpdate 的解决方案始终确保内容同步,我相信会起作用,在每个渲染过程中闪光。


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.

Example:

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

vs

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

解决方案

Yes there is a difference!

The immediate effect of using innerHTML versus dangerouslySetInnerHTML is identical -- the DOM node will update with the injected 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.

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.

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.

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 vs dangerouslySetInnerHTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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