高级前端
react
【Q068】React Portal 有哪些使用场景

React Portal 有哪些使用场景

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

Author 回答者: shfshanyue (opens in a new tab)

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 in a new tab)

<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);
  }
}