我想使用 React 在整个 DOM 中多次添加组件。 This fiddle显示了我想要做什么,并且它不会引发任何错误。代码如下:
HTML:
<div id="container">
<!-- This element's contents will be replaced with the first component. -->
</div>
<div id="second-container">
<!-- This element's contents will be replaced with the second component. -->
</div>
JS:
var Hello = React.createClass({
render: function() {
return <div>Hello {this.props.name}</div>;
}
});
React.render(<Hello name="World" />, document.getElementById('container'));
React.render(<Hello name="Second World" />, document.getElementById('second-container'));
我见过this question我担心通过执行上述操作,我将冒着 React 组件相互干扰的风险。该问题的答案建议使用服务器端渲染,但这对我来说不是一个选项,因为我使用的是 Django 服务器端。
另一方面,也许我正在做的事情是可以的,因为我只安装了一个 React 库实例(而不是多个组件调用自己的 React 实例)?
这种使用多个 DOM 实例的方式是使用 React 的好方法吗?
最佳答案
是的,在同一页面上多次调用 React.render
是完全可以的。正如您所建议的,React 库本身仅加载一次,但每次调用 React.render
都会创建一个独立于任何其他组件的新组件实例。 (事实上,这种情况在正在过渡到 React 的网站上并不罕见,其中页面的某些部分是使用 React.render
生成的,而其他部分则不是。)
关于reactjs - 在 DOM 中多次使用 React.render() 可以吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31302803/