React中发送验证码,倒计时

render () {

  return (

    <label>验 证 码:</label>

    <div className="flexBetween">
      <Input type="text" className="code-input" value={code} onChange={this.onChange.bind(this, 'code')} placeholder="请输入" autoComplete="off" />
      <Button type="primary" className="code-btn" onClick={this.onChange.bind(this, 'sendCode')}>
        { isSend ? count + 's' : '发送验证码'}
      </Button>
    </div>

  )

}

 

this.state = {

  isSend: false,

  count: 60,

}

 

onChange(key, value) {
  const { tell } = this.state
  if (key === 'sendCode') {
    this.setInterval()
  }
}

setInterval = () => {
  this.timer = setInterval(this.countDown, 1000)
}
 
countDown = () => {
  const { count } = this.state
  if (count === 1) {
    this.clearInterval()
    this.setState({ isSend: false, count: 60 })
  } else {
    this.setState({ isSend: true, count: count - 1 })
  }
}
 
clearInterval = () => {
  clearInterval(this.timer)
}
posted @ 2021-05-17 15:11  搬砖的苦行僧  阅读(312)  评论(0编辑  收藏  举报