我想使用React在整个DOM中多次添加组件。这个小提琴显示了我要执行的操作,并且不会引发任何错误。这是代码:
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'));
我已经看过这个问题了,恐怕通过上述操作,我将冒使React组件相互干扰的风险。该问题的答案建议使用服务器端渲染,这对我来说不是一个选择,因为我正在使用Django服务器端。
另一方面,也许我在做什么就可以了,因为我只安装了一个React库实例(而不是多个组件调用自己的React实例)?
使用多个DOM实例的这种方法是使用React的一种好方法吗?
是的,React.render在同一页面上多次调用是完全可以的。就像您建议的那样,React库本身仅加载一次,但是每次调用React.render都会创建一个独立于其他组件的新组件实例。(实际上,这种情况在过渡到React的站点上并不少见,其中页面的某些部分是使用生成的,React.render而其他部分不是。)
React.render