最近在写项目的时候碰到一个倒计时的需求,然后我就简单封装了一下,需要的可以自取。
import React, { useEffect } from "react";
import { Button } from "antd";
function Count({ duration }) {
const [time, setTime] = React.useState(duration || 60);
const [timeId, setTimeId] = React.useState("");
useEffect(() => {
if (time < 1) {
clearInterval(timeId);
setTime(duration || 60);
}
}, [time]);
/**
* @description: 点击开始倒计时
* @return {*}
*/
const countdown = () => {
setTime((time) => time - 1);
setTimeId(setInterval(() => setTime((time) => time - 1), 1000));
};
return (
<div>
<Button onClick={countdown} disabled={time < duration && time > 0}>
{time === duration || time === 0 ? "获取验证码" : `${time}秒后获取`}
</Button>
</div>
);
}
export default Count;