src/Pages/DialogPage.js
import React,{useState} from 'react';
import Dialog from '../components/Dialog';
const DialogPage = () => {
const [showDialog,setShowDialog] = useState(false)
return (
<div className="dialogPage">
<h1>DialogPage</h1>
<button onClick={() => setShowDialog(!showDialog)}>toggle</button>
{
showDialog && <Dialog/>
}
</div>
);
}
export default DialogPage;
src/components/Dialog.js
import React, { Component } from 'react'
//传送门
import {createPortal} from "react-dom";
export default class Dialog extends Component {
//多包一层div
constructor(props){
super(props);
const doc = window.document;
this.node = doc.createElement("div");
doc.body.appendChild(this.node);
}
componentWillUnmount(){
window.document.body.removeChild(this.node);
}
render() {
//把弹窗放在body下 传送门 传2个参数
return createPortal(
<div className="dialog">
<h1>Dialog</h1>
</div>,this.node
);
}
}
网友评论