import { Button, Input } from 'antd'
let timer
const Btn = () => {
const [time, setTime] = useState(5)
const [btnDisabled, setBtnDisabled] = useState(false)
const [phone, setPhone] = useState()
const [btnContent, setBtnContent] = useState('获取验证码')
useEffect(() => {
clearInterval(timer)
return () => clearInterval(timer)
}, [])
useEffect(() => {
if (time > 0 && time < 60) {
setBtnContent(`${time}s后重发`)
} else {
clearInterval(timer)
setBtnDisabled(false)
setTime(60)
}
}, [time])
const getCaptcha = () => {
if (!phone) return
timer = setInterval(() => setTime(pre =>pre-1), 1000)
setBtnDisabled(true)
}
const onChangePhone = (e) => {
setPhone(e.target.value)
}
return (
<div>
<Input value={phone} onChange={onChangePhone}/>
<Button disabled={btnDisabled} onClick={getCaptcha}>
{!btnDisabled ? '获取验证码': `${time}s后重发`}
</Button>
</div>
)
}
export default Btn
react hooks实现一个手机验证码倒计时功能
最新推荐文章于 2024-06-24 18:18:16 发布