关于前端:React-简易版-全局message方法

44次阅读

共计 770 个字符,预计需要花费 2 分钟才能阅读完成。

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

正文完
 0