React实战之60s倒计时按钮(发送短信验证按钮)

导入:(antd组件——Form表单

import { Button, Form, Input } from 'antd';
const FormItem = Form.Item;
 
state = {
  loading: false,
  yztime: 59,
};
 
//倒计60s
count = () => {
  let { yztime } = this.state;
  let siv = setInterval(() => {
    this.setState({ yztime: (yztime--) }, () => {
      if (yztime <= -1) {
        clearInterval(siv);  //倒计时( setInterval() 函数会每秒执行一次函数),用 clearInterval() 来停止执行:
        this.setState({ loading: false, yztime: 59 })
      }
    });
  }, 1000);
}
 
//短信验证
verifiedSubmit = (e) => {
  this.setState({ loading: true });
  e.preventDefault();
  this.props.form.validateFields((err, values) => {
    if (!this.state.yztime == 0) {
      this.count();
    }
    let verify = { phone: values.accountname, gettype: 1 }
    this.props.dispatch({ type: 'login/verify', payload: { verify } });
  });
}
 
render() {
  const { form: { getFieldDecorator } } = this.props;
  return (
    <Form>
      <FormItem>
        {getFieldDecorator('yzm', {
          rules: [{ required: false, message: '请输入验证码!' }],
        })(<Input placeholder="请输入验证码" />
        )}
        <Button loading={this.state.loading} htmlType="submit" onClick={this.verifiedSubmit}>
        {this.state.loading ? this.state.yztime + '秒' : '发送验证'}
        </Button>
      </FormItem>
    </Form>
  );
}
 
 
 
代码就这样了!
小生的第一篇博客,如有不足之处,还望多多指教

猜你喜欢

转载自www.cnblogs.com/Yu-Shuai/p/10785012.html