likes
comments
collection
share

React 简易版 全局message方法

作者站长头像
站长
· 阅读数 39
import React, { memo } from "react";
import ReactDOM from 'react-dom';


const Message = memo((props) => {
    // console.log('msg:', props)
    return (
        <div className="absolute pt-[50rem] text-white flex justify-center  w-full z-[100]">
            <div className="bg-[#222222] px-5 py-[1.375rem] rounded-lg"> {props.msg || '已提交'}</div>
        </div>
    )
})

let timer = null

const messageTip = {
    show(msg) {
        let el = document.getElementById('#message-wrap');
        // 这一步是必要的的,因为在执行到这里的时候,页面还没有挂载,所以获取不到el节点
        if (!el) {
            el = document.createElement('div')
            el.style.position = 'absolute'
            el.style.top = '0'
            el.style.width = '100%'
            el.id = 'message-wrap'
            document.body.append(el)
            ReactDOM.render(<Message msg={msg} />, el);
        }
        if (el) {
            timer = setTimeout(() => {
                document.body.removeChild(document.getElementById('message-wrap'))
            }, 3000);
        }
        if (!el && timer) {
            clearTimeout(timer)
        }

    },
}

export default messageTip
转载自:https://segmentfault.com/a/1190000042355066
评论
请登录