【问题标题】:May i render the react-portal inside my react application?我可以在我的反应应用程序中渲染反应门户吗?
【发布时间】:2018-04-20 17:40:45
【问题描述】:

我使用 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>

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

【问题讨论】:

    标签: reactjs portal


    【解决方案1】:

    portal 的想法是你可以在 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,
      );
    }
    

    【讨论】:

      猜你喜欢
      • 2018-08-31
      • 2018-02-23
      • 1970-01-01
      • 1970-01-01
      • 2021-05-15
      • 2018-01-08
      • 2023-03-15
      • 1970-01-01
      • 2021-08-24
      相关资源
      最近更新 更多