同时最多只展示一个toast提示

回到文章>>

COPYHTML

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

COPYJAVASCRIPT

const { Component, useState } = React; let toastInstance = false; const toast = (text, duration = 1800, container = document.body) => { if (toastInstance) { return; } toastInstance = true; let div = document.createElement("div"); div.className = "toast"; div.style.cssText = `position: fixed; padding: 12px 20px; border-radius: 5px; top: 20px; left: 50%; transform: translate3d(-50%, 0, 0); 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); // 固定时间后消失 toastInstance = false; resolve(); }, duration); }); }; const sleep = (timeout) => { return new Promise((resolve) => { setTimeout(() => { resolve(); }, timeout); }); }; /** * toast的顺序控制 * 之前是一个toast正在进行中时,其他的toast直接被忽略掉 * 现在会把将要弹出的toast存储起来,然后按照顺序弹出 */ let toastList = []; const toastWaterFall = async (text) => { if (toastInstance) { toastList.push(text); } else { await toast(text); if (toastList.length) { while (toastList.length) { await sleep(300); await toast(toastList.shift() + ""); } } } }; const Home = () => { const [counter, setCounter] = useState(0); const hadneOneClick = () => { toastWaterFall(counter); setCounter(counter + 1); }; return ( <div className="home"> <p>同时点击N多下试试!</p> <button onClick={hadneOneClick}>同时最多提示一个</button> </div> ); }; ReactDOM.render(<Home />, document.getElementById("app"));
新窗口打开