是否可以让 React 忽略子树?即,不比较或更新它?
我的用例正在迁移到 React。一次重写我们所有的 Handlebars 模板是不可行的,但是如果我们可以将现有模板用于某些子组件,我们可以随着时间的推移慢慢采用它。
是否可以让 React 忽略子树?即,不比较或更新它?
我的用例正在迁移到 React。一次重写我们所有的 Handlebars 模板是不可行的,但是如果我们可以将现有模板用于某些子组件,我们可以随着时间的推移慢慢采用它。
是的,如果您不修改 React 中的子树,那么根本不会触及 DOM。在 React 中包装非 React 功能(如 Handlebars 模板)很容易。您可以使用dangerouslySetInnerHTML
:
render: function()
return <div dangerouslySetInnerHTML={{__html: template(values)}}>;
}
或者您可以简单地返回一个空 div 并在 componentDidMount 中填充(或附加事件处理程序等)它:
render: function()
return <div />;
},
componentDidMount: function() {
var node = React.findDOMNode(this);
node.innerHTML = template(values);
}
在后一种情况下,React 在初始渲染后不会接触 DOM,因为render
总是返回相同的东西。
看看这个模块。简单而且非常有效。 https://gist.github.com/alexeisavca/d4ff175fd16c93c8785d
这是它的咖啡脚本版本。
module.exports = ReactIgnore = React.createClass
shouldComponentUpdate: ->
false
render: ->
React.Children.only @props.children
并将您的组件包装在其中:
<ReactIgnore>
YourComponent
</ReactIgnore>