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

pla*_*sss 3 portal reactjs

我使用 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>
Run Code Online (Sandbox Code Playgroud)

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

<html>
  <body>
    <div id="app-root"></div>
    <div id="modal-root"></div>
  </body>
</html>
Run Code Online (Sandbox Code Playgroud)

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

Shu*_*tri 5

门户的想法是你可以在 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,
  );
}
Run Code Online (Sandbox Code Playgroud)