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