我想使用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>
Run Code Online (Sandbox Code Playgroud)
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'));
Run Code Online (Sandbox Code Playgroud)
我已经看到了这个问题,我担心通过上面的操作,我会冒险让React组件相互干扰.这个问题的答案建议使用服务器端渲染,这对我来说不是一个选项,因为我正在使用Django服务器端.
另一方面,也许我正在做的是好的,因为我只安装了一个React库的实例(而不是多个组件调用它们自己的React实例)?
这种使用多个DOM实例的方式是否可以使用React?
hop*_*per 108
是的,React.render在同一页面上多次调用是完全可以的.正如您所建议的那样,React库本身只加载一次,但每次调用React.render都会创建一个独立于其他组件的新组件实例.(事实上,在转换到React的过程中,这种情况并不少见,其中页面的某些部分是使用生成的,React.render而其他部分则不是.)
| 归档时间: |
|
| 查看次数: |
37806 次 |
| 最近记录: |