我想使用 React 在整个 DOM 中多次添加组件。这把小提琴 http://jsfiddle.net/ypcrumble/gs7k1kth/1/显示了我想要做什么,并且它不会引发任何错误。这是代码:
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'));
我见过这个问题 https://stackoverflow.com/q/27112274/2532070我担心通过执行上述操作,我将冒着 React 组件相互干扰的风险。这个问题的答案建议使用服务器端渲染,这对我来说不是一个选择,因为我使用的是 Django 服务器端。
另一方面,也许我正在做的事情没问题,因为我只安装了一个 React 库实例(而不是多个组件调用自己的 React 实例)?
这种使用多个 DOM 实例的方式是使用 React 的好方法吗?
是的,打电话就可以了React.render
在同一页面上多次。正如您所建议的,React 库本身仅加载一次,但每次调用React.render
将创建一个独立于任何其他组件的新组件实例。 (事实上,这种情况在正在过渡到 React 的网站上并不罕见,其中页面的某些部分是使用React.render
而其他人则不然。)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)