美文网首页
React传送门实现弹框

React传送门实现弹框

作者: key君 | 来源:发表于2019-11-01 17:25 被阅读0次

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
        );
    }
}

相关文章

网友评论

      本文标题:React传送门实现弹框

      本文链接:https://www.haomeiwen.com/subject/epkqbctx.html