gpt4 book ai didi

reactjs - 我可以在我的 React 应用程序中渲染 React-portal 吗?

转载 作者:行者123 更新时间:2023-12-03 14:13:31 25 4
gpt4 key购买 nike

我使用react 16。我想像这样在我的应用程序中渲染门户:

<html>
<body>
<div id="app-root">
<div>...My app stuff</div>
<div id="modal-root">... portal stuff</div> <-- portal content
</div>
</body>
</html>

但官方文档建议在旁边渲染门户,而不是在应用程序中。

<html>
<body>
<div id="app-root"></div>
<div id="modal-root"></div>
</body>
</html>

这是使用门户的唯一正确方法吗?

最佳答案

portal 的想法是你可以在 DOM 树中的任何位置渲染它,你所需要的只是一个有效的 DOM 节点来渲染它,它不必位于 app-root

根据文档

However, sometimes it’s useful to insert a child into a different location in the DOM:

render() {
// React does *not* create a new div. It renders the children into `domNode`.
// domNode is any valid DOM node, regardless of its location in the DOM.
return ReactDOM.createPortal(
this.props.children,
domNode,
);
}

关于reactjs - 我可以在我的 React 应用程序中渲染 React-portal 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47172870/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com