//model.jsximport React from 'react';import ReactDOM from 'react-dom';const modalDivElement = document.getElementById("modal");export default function Modal({ children }) {const style={display: "flex",justifyContent: "center",alignItems: "center",position: "absolute",top: 0,left: 0,right: 0,bottom: 0,background:' rgba(0, 0, 0, .5)',}const modalContent = (<divstyle={style}>{children}</div>);return ReactDOM.createPortal(modalContent, modalDivElement);}
//app.jsximport Modal from "./component/Model"import React,{useState} from "react"function App() {const [isShow, setIsShow] = useState(false);const clickHandle= (e)=> {setIsShow(!isShow);}const btnStyle={width:'90px',height:'30px',backgroundColor:'#88D0FF',borderRadius: "10px",color:'#fff',textAlign:'center',lineHeight:'30px',padding:'5px',margin:'20px',userSelect:'none',cursor:'pointer'}return (<divstyle={btnStyle}onClick={clickHandle}>按钮{isShow && (<Modal><span>王苏</span></Modal>)}</div>)}export default App;
public文件夹下的index.html需要有两个根标签
<div id="root"></div><div id="modal"></div>
