zoukankan      html  css  js  c++  java
  • React.createPortal 及 Modal 的新实现方式

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

    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
        );
      }
    }
     
     
     
  • 相关阅读:
    PHP
    Python语言特性
    Selenium2+python自动化
    Linux命令--系统管理
    Linux命令--网络管理
    Linux命令--压缩解压(简化版)
    Linux--压缩解压命令
    Linux命令--用户管理
    Linux命令--获取帮助
    Linux命令--权限管理
  • 原文地址:https://www.cnblogs.com/Ewarm/p/13667130.html
Copyright © 2011-2022 走看看