今天有看到同事写的代码,

ReactDOM.createPortal,哦豁这是什么API没有使用过
然后百度了一下,原来这个API可以使自己写的组件或者元素挂载到任意你你想挂载的dom元素上,
 
ReactDOM.createPortal的使用方法
react-dom 提供的具体方法是ReactDOM.createPortals(child,container) ,该方法需要两个参数,第一个参数是需要挂载的组件实例,而第二个参数则是要挂载到DOM节点。
一般来说第一个参数可能需要传递的是需要挂载的this.props.children
 
我们可以利用这个API将自己写的弹窗挂载到body上面。
class ModalContainer extends Component {
  constructor(props) {
    super(props);
    this.el = document.body;
  }
  componentDidMount() {
    modalRoot.appendChild(this.el);
  }
  componentWillUnmount() {
    modalRoot.removeChild(this.el);
  }
  render() {
    return ReactDOM.createPortal(
      this.props.children,
      this.el
    );
  }
}
 
 
 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-06-03
  • 2021-11-28
  • 2022-02-09
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-11-12
  • 2022-12-23
  • 2022-12-23
  • 2022-02-10
  • 2022-01-14
相关资源
相似解决方案