在 DOM 中多次使用 React.render() 可以吗? [英] Is it OK to use React.render() multiple times in the DOM?

查看:87
本文介绍了在 DOM 中多次使用 React.render() 可以吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 React 在整个 DOM 中多次添加组件.这个小提琴 显示了我想要做的事情,并且不会抛出任何错误.代码如下:

HTML:

<!-- 此元素的内容将替换为第一个组件.-->

<div id="第二个容器"><!-- 此元素的内容将替换为第二个组件.-->

JS:

var Hello = React.createClass({渲染:函数(){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 生成的,而其他部分则不是.)

I want to use React to add components multiple times throughout the DOM. This fiddle shows what I'm looking to do, and it doesn't throw any errors. Here's the code:

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'));

I've seen this question and I'm afraid that by doing the above, I'll be risking having React components interfere with each other. The answer to that question suggests using server-side rendering which isn't an option for me as I'm using Django server-side.

On the other hand, maybe what I'm doing is OK because I only have one instance of the React library mounted (as opposed to multiple components calling their own instance of React)?

Is this way of using multiple DOM instances an OK way to use React?

解决方案

Yes, it is perfectly fine to call React.render multiple times on the same page. Just as you've suggested, the React library itself is only loaded once, but each call to React.render will create a new component instance independent of any others. (In fact, such a situation is not uncommon on sites that are in the process of transitioning to React, where some portions of the page are generated using React.render and others are not.)

这篇关于在 DOM 中多次使用 React.render() 可以吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆