极客时间返利平台,你可以在上边通过山月的链接购买课程,并添加我的微信 (shanyue94) 领取返现。
山月训练营之面试直通车 服务上线了,从准备简历、八股文准备、项目经历准备、面试、面经、面经解答、主观问题答复、谈薪再到入职的一条龙服务。

# React Portal 有哪些使用场景

Issue

欢迎在 Gtihub Issue 中回答此问题: Issue 69 (opens new window)

Portals provide a first-class way to render children into a DOM node that exists outside the DOM hierarchy of the parent component.

在以前, react 中所有的组件都会位于 #app 下,而使用 Portals 提供了一种脱离 #app 的组件。

因此 Portals 适合脱离文档流(out of flow) 的组件,特别是 position: absoluteposition: fixed 的组件。比如模态框,通知,警告,goTop 等。

以下是官方一个模态框的示例,可以在以下地址中测试效果 https://codepen.io/gaearon/pen/jGBWpE?editors=1010 (opens new window)

<html>
  <body>
    <div id="app"></div>
    <div id="modal"></div>
    <div id="gotop"></div>
    <div id="alert"></div>
  </body>
</html>
const modalRoot = document.getElementById("modal");

class Modal extends React.Component {
  constructor(props) {
    super(props);
    this.el = document.createElement("div");
  }

  componentDidMount() {
    modalRoot.appendChild(this.el);
  }

  componentWillUnmount() {
    modalRoot.removeChild(this.el);
  }

  render() {
    return ReactDOM.createPortal(this.props.children, this.el);
  }
}
Last Updated: 11/27/2021, 6:11:48 PM