import React, { useState, useEffect, useCallback, useRef } from 'react';
const CountDown: React.FC = () => {
const intervalRef = useRef<any>(null);
const [count, changeCount] = useState(0);
// 组件卸载时清除计时器
useEffect(() => {
return () => {
clearInterval(intervalRef.current);
};
}, []);
useEffect(() => {
if (count === 59) {
intervalRef.current = setInterval(() => {
changeCount((preCount) => preCount - 1);
}, 1000);
} else if (count === 0) {
clearInterval(intervalRef.current);
}
}, [count]);
const onGetCaptcha = useCallback(() => {
changeCount(59);
}, []);
return (
<button type='button' disabled={!!count} onClick={onGetCaptcha}>
{count ? `${count} s` : '获取验证码'}
</button>
);
};
export default CountDown;
用React hook写一个倒计时
最新推荐文章于 2024-05-24 21:28:03 发布