用传送门封装弹框

108 阅读1分钟

弹框调用

class App extends React.Component{
      constructor(props){
        super(props);
        this.state={
          showDialog:false
        }
      }
      render(){
        const { showDialog} = this.state;
        return (
          <div className="app">
            <button onClick = {() => this.setState({ showDialog:!showDialog})}>toggle</button>
            {
              showDialog && (
                <Dialog hideDialog = {() => this.setState({ showDialog: false })}>
                  <h2>添加成功</h2>
                </Dialog>
              )
            }
          </div>
        )
      }
    }

弹框实现: ReactDOM.createPortal(child, container)

class Dialog extends React.Component {
      constructor(props) {
        super(props);
        const doc = window.document;
        this.node = doc.createElement('div');
        doc.body.appendChild(this.node);
      }
      componentWillUnmount() {
        // 清除关闭弹窗剩余的垃圾div
        if (this.node) {
          window.document.body.removeChild(this.node)
        }
      }
      render() {
        const { hideDialog, children} = this.props;
        return ReactDOM.createPortal(
          <div className="dialog">
           {children}
           {
            typeof hideDialog ==="function" && (
              <button onClick={hideDialog}>关闭</button>
            )
           }
          </div>,
          this.node
        )
      }
    }