类ant design的toast提示

回到文章>>

COPYHTML

<div id="app"></div>

COPYJAVASCRIPT

const { Component, useState } = React; const toast = (text, duration = 1800, container = document.body) => { let div = document.createElement("div"); div.className = "toast"; div.style.cssText = `position: relative; margin-top: 20px; padding: 12px 20px; border-radius: 5px; background-color: rgba(255, 255, 255, 0.96); box-shadow: 0 0 2px #666666; color: #111111; font-size: 16px; line-height: 1.5; white-space: nowrap; text-align: center;`; div && (div.innerHTML = text.toString()); container.appendChild(div); return new Promise((resolve) => { setTimeout(() => { div && div.parentNode && div.parentNode.removeChild(div); // 固定时间后消失 resolve(); }, duration); }); }; let toastContainer = null; const getToastContainer = () => { if (toastContainer) { return toastContainer; } toastContainer = document.createElement("div"); toastContainer.style.cssText = `position: fixed; top: 20px; left: 50%; transform: translate3d(-50%, 0, 0); z-index: 9999;`; document.body.appendChild(toastContainer); return toastContainer; }; const message = (text) => { getToastContainer(); toast(text, 1800, toastContainer); }; const Home = () => { const [counter, setCounter] = useState(0); const handleClick = () => { message(counter); setCounter(counter + 1); }; return ( <div className="home"> <button onClick={handleClick}>显示提示</button> </div> ); }; ReactDOM.render(<Home />, document.getElementById("app"));
新窗口打开