ceatePotral的使用

167 阅读1分钟
 import React from "react"
 import {createPortal} from 'react-dom'
 
 export default class Dialog extends Component{
    constructor(props){
        super(props)
        const doc=window.document;
        this.node=doc.createElement("div")
        doc.body.appendChild(this.node);
        
    }
    componentWillUnmount(){
      if(this.node){
        window.document.body.removeChild(this.node)
       }
    }
    render(){
      return createPortal(
        <div className="dialog">
           <h3>Diolog</h3>
         </div>,
         this.node
      )
    }
 
 }

调用Dialog组件

 import React,{Component} from “react"
 import Dialog from "../componet/Dialog";
 export default class DialogPage extends Component{
    constructor(props){
      super(props)
      this.state={
        showDialoginf:false
       }
    }
    render(){
      const {showDialog}=this.state;
      return(
        <div className="dialogPage border">
             <h3>Dialogpage</h3>
             <button onClick={()=>{
               this.setState({showDialog:!showDialog});
               
             }}>
             click   
             </button>
             {showDialog && <Dialog />
        <div>
      )
    }
 }