react hooks实现一个手机验证码倒计时功能

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

猜你喜欢

转载自blog.csdn.net/zm_miner/article/details/123742686