React倒计时若干种实现方法
作者:互联网
html:
<Button type="link" onClick={HandleSubmit} disabled={disableFlag}>{linkText}</Button>变量定义:
const [disableFlag, setDisable] = useState<boolean>(false) const[linkText,setLinkText]=useState<string>('获取验证码')
1.原始版:
代码:
let num =10 let [num,setDisableSeconds]=useState<number>(10) const HandleSubmit = () => { setDisable(true); let x = setInterval(() => { if(num>0) { num=num-1; } setLinkText(num+''); if(num==0) { clearInterval(x); setDisable(false); setLinkText(linkText); } }, 1000); }
2.进阶版:
let newTimer =null; const [num, setDisableSeconds] = useState(10); const HandleSubmit = () => { setDisable(true); newTimer = setInterval(() => { if (num > 0) { setDisableSeconds((c) => c - 1); } }, 1000); } useEffect(()=>{ if(disableFlag){ setLinkText(num+''); if(num<0){ clearInterval(newTimer); setDisable(false); } } else { setLinkText('获取验证码'); } })
标签:倒计时,const,React,num,useState,setLinkText,若干种,let,setDisable 来源: https://www.cnblogs.com/jizhong/p/16419068.html