react实战 倒计时获取短信验证码

constructor(props) {
    super(props);
    this.state = {
      count: 60, // 秒数初始化为60秒
      getCodeChange: true, // 文案默认为 '获取验证码'
    }
  }

// 获取验证码
  getValidateCode(){
    let state = this.state;
    this.props.form.validateFields((err, values) => {
      if (!err) {
        if (!state.getCodeChange) {
          return
        }
        let count = state.count
        const timer = setInterval(() => {
          this.setState({
            getCodeChange:false,
            count: (count--)
          }, () => {
            if (count === 0) {
              clearInterval(timer);
              this.setState({
                getCodeChange: true,
                count: 60
              })
            }
          })
        }, 1000)
        fetch.post('/api/vanke/getVerificationCode', {
          phone:values.tel
        }).then((response) => {
          this.setState({
            smsValidateCode:response.results
          })
        }).catch((err) => {
          Dialog.error({
            title: '错误',
            content: err.message
          });
        });
      }
    });
  }



render(){
let getCodetext = '获取验证码';
    if(!state.getCodeChange){
      getCodetext = state.count+'s';
    }

<div className="validate-code-wrap">
      <a className="get-validate-code" onClick = {this.getValidateCode.bind(this)}>
          {getCodetext}
      </a>
</div>
}

表单组件基于antd,post基于封装好的方法,在这里不做引用。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容