Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
663 views
in Technique[技术] by (71.8m points)

reactjs - Is it OK to use React.render() multiple times in the DOM?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...