我可以在react应用程序中渲染react-portal吗?

时间:2017-11-08 06:21:05

标签: reactjs portal

我使用了反应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>

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

1 个答案:

答案 0 :(得分:2)

门户网站的想法是你可以在DOM树中的任何地方渲染它,你需要的只是一个有效的DOM节点来渲染它,它不一定要在app-root的旁边

根据文档

  

但是,有时将孩子插入不同的孩子会很有用   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,
  );
}
相关问题