点击就产生60秒倒计时的按钮->点击后就会执行某操作,立刻开启倒计时x秒,倒计时结束才能再次能够点击。
作者:互联网
点击就产生60秒倒计时的按钮
点击后就会执行某操作,立刻开启倒计时x秒,倒计时结束才能再次能够点击。
export function subscribeInterval(ms, task) {
const handle = setInterval(task, ms);
return () => clearInterval(handle);
}
export const useInterval = (ms, task) => useEffect(() => subscribeInterval(ms, task), []);
export function CountDownButton({countDown, normalText, waitText, task, ...props}) {
const [count, setCount] = useState(0);
const [isWait, setIsWait] = useState(false);
const timer = useRef(-1);
// const wait = ()=>{
// clearInterval(timer.current);
// timer.current = setInterval(()=>{
// setCount(count => count -1);
// if(count <= 0){
// setIsWait(false);
// clearInterval(timer.current);
// setCount(countDown);
// console.log(count);
// console.log("??");
// }
// }, 1000);
// };
useEffect(()=>{
clearInterval(timer.current);
timer.current = setInterval(()=>{
setCount(count => count -1);
console.log(count)
if(count == 0){
setIsWait(false);
clearInterval(timer.current);
console.log(count);
console.log("??");
}
}, 1000);
}, [count]);
// useEffect(()=>{
// console.log("111");
// setCount(countDown);
// },[countDown])
return <>
<Button type="primary" disabled={isWait} onClick={() => {
task();
setIsWait(true);
setCount(countDown);
}} {...props}>{isWait ?count + "秒后" + waitText : normalText}</Button>
</>
}
标签:count,60,task,const,current,setCount,timer,倒计时,点击 来源: https://www.cnblogs.com/peekapoooo/p/14248064.html