ReactDOM.render
就像 React 应用程序的 main 方法。所有与 React 相关的概念,如组件、状态和上下文都从这里开始。您可以致电ReactDOM.render
使用相同容器 DOM 节点或不同容器 DOM 节点在同一页面上多次。如果容器相同,这将对其执行更新,并且仅根据需要改变 DOM 以反映最新的 React 元素。但如果容器节点不同,它将创建两个不同的 React 根,并且它们完全独立。这两个 React 根之间没有共享状态或上下文,这非常像在同一页面上运行两个不同的 React 应用程序。
另外,在渲染根元素之后ReactDOM.render
到容器节点中,所有其他后代元素都将由 React 在其中渲染,并且我们没有任何控制权来更改它们的渲染位置(这将来会改变)。
因此,在您的情况下,如果您想在不同的容器节点中渲染这两个组件,您将无法拥有一个保持共享状态或事件处理的 App 组件。但除此之外,您还可以创建两个不同的 React 根,并通过 props 在它们之间共享对象和方法。
const data = {/*...*/}
ReactDOM.render(<Component data={data} />,
document.getElementById('component'));
ReactDOM.render(<AnotherComponent data={data} />,
document.getElementById('anotherComponent'));
但是,如果您想在某个时候更改这些道具,则必须手动重新渲染根组件。举个例子,如果你有一个counter
每秒都会更新的变量,您必须使用每个新值重新渲染根。
let couter = 0
setInterval(function(){
counter++
ReactDOM.render(<Component data={data} />,
document.getElementById('component'));
ReactDOM.render(<AnotherComponent data={data} />,
document.getElementById('anotherComponent'));
}, 1000)
另一个好的选择是使用类似 Redux 的状态管理库。你可以有一个store
并在两个根之间共享它。如果您需要在两个根之间共享非常复杂的状态,我强烈推荐这种方法。
const store = createStore(/* ... */)
// ...
ReactDOM.render(
<Provider store={store}>
<Component />
</Provider>,
document.getElementById('component')
);
ReactDOM.render(
<Provider store={store}>
<AnotherComponent />
</Provider>,
document.getElementById('anotherComponent')
);
当您使用 Redux 时,您将连接您的Component
and AnotherComponent
to the store
with connect https://github.com/reactjs/react-redux/blob/master/docs/api.md#connectmapstatetoprops-mapdispatchtoprops-mergeprops-options高阶分量。在幕后,这将订阅 http://redux.js.org/docs/api/Store.html#subscribe你的组件store
使用组件的状态更改时更改并重新渲染组件forceUpdate https://facebook.github.io/react/docs/react-component.html#forceupdate方法。所以你不必手动调用ReactDOM.render
方法,只要您通过将操作分派到商店来更改状态即可。