Skip to content

React Portals 使用场景(高级)

Portals 传送门

  • 组件默认会按照既定层次嵌套渲染
  • 如何让组件渲染到父组件以外? Portals

Portals 使用场景

  • overflow:hidden
  • 父组件 z-index 值太小
  • fixed 需要放在 body 第一层级

例子,css 文件

css
.modal {
  position: fixed;
  width: 300px;
  height: 100px;
  top: 100px;
  left: 50%;
  margin-left: -150px;
  background-color: #000;
  color: #fff;
  text-align: center;
  /*opacity: 0.2;*/
}

组件 PortalsDemo.js

js
import React from 'react';
import ReactDom from 'react-dom';
import './style.css';

class PortalsDemo extends React.Component {
  constructor(props) {
    super(props);
    this.state = {};
  }

  render() {
    // 正常渲染
    // return <div className="modal">
    //   {/*类似 Vue slot*/}
    //   {this.props.children}
    // </div>

    // 使用 Portals 渲染到 body 上
    return ReactDom.createPortal(
      <div className="modal">
        {/*类似 Vue slot*/}
        {this.props.children}
      </div>,
      document.body, // DOM 节点
    );
  }
}

export default PortalsDemo;

在 App.js 中使用

js
<PortalsDemo> modal 内容</PortalsDemo>

基于 MIT 许可发布