1. //model.jsx
    2. import React from 'react';
    3. import ReactDOM from 'react-dom';
    4. const modalDivElement = document.getElementById("modal");
    5. export default function Modal({ children }) {
    6. const style={
    7. display: "flex",
    8. justifyContent: "center",
    9. alignItems: "center",
    10. position: "absolute",
    11. top: 0,
    12. left: 0,
    13. right: 0,
    14. bottom: 0,
    15. background:' rgba(0, 0, 0, .5)',
    16. }
    17. const modalContent = (
    18. <div
    19. style={style}
    20. >
    21. {children}
    22. </div>
    23. );
    24. return ReactDOM.createPortal(modalContent, modalDivElement);
    25. }
    1. //app.jsx
    2. import Modal from "./component/Model"
    3. import React,{useState} from "react"
    4. function App() {
    5. const [isShow, setIsShow] = useState(false);
    6. const clickHandle= (e)=> {
    7. setIsShow(!isShow);
    8. }
    9. const btnStyle={
    10. width:'90px',
    11. height:'30px',
    12. backgroundColor:'#88D0FF',
    13. borderRadius: "10px",
    14. color:'#fff',
    15. textAlign:'center',
    16. lineHeight:'30px',
    17. padding:'5px',
    18. margin:'20px',
    19. userSelect:'none',
    20. cursor:'pointer'
    21. }
    22. return (
    23. <div
    24. style={btnStyle}
    25. onClick={clickHandle}
    26. >
    27. 按钮
    28. {isShow && (
    29. <Modal>
    30. <span>王苏</span>
    31. </Modal>
    32. )}
    33. </div>
    34. )
    35. }
    36. export default App;

    public文件夹下的index.html需要有两个根标签

    1. <div id="root"></div>
    2. <div id="modal"></div>