1.定义定时器和变量
const [countdown, setCountdown] = useState(5); // 初始倒计时时间为 60 秒
const [isCounting, setIsCounting] = useState(false); // 是否正在倒计时
let [wenzi,setwenzi]=useState('获取验证码')
const startCountdown = () => {
setIsCounting(true);
};
useEffect(() => {
let timer;
if (isCounting && countdown > 0) {
// 开始倒计时
timer = setInterval(() => {
setCountdown(prevCountdown => prevCountdown - 1);
setwenzi(`${countdown} 秒后重发`)
}, 1000);
}else{
setwenzi(`获取验证码`)
}
// 清理定时器
return () => {
clearInterval(timer);
};
}, [isCounting, countdown]);
2.按钮绑定
<button onClick={startCountdown} disabled={isCounting || countdown !== 5}>
{wenzi}
</button>