React实战之60s倒计时按钮——短信验证按钮
导入:(antd组件——Form表单)
1 import { Button, Form, Input } from 'antd'; 2 const FormItem = Form.Item; 3 4 state = { 5 loading: false, 6 yztime: 59, 7 }; 8 9 //倒计60s 10 count = () => { 11 let { yztime } = this.state; 12 let siv = setInterval(() => { 13 this.setState({ yztime: (yztime--) }, () => { 14 if (yztime <= -1) { 15 clearInterval(siv); //倒计时( setInterval() 函数会每秒执行一次函数),用 clearInterval() 来停止执行: 16 this.setState({ loading: false, yztime: 59 }) 17 } 18 }); 19 }, 1000); 20 } 21 22 //短信验证 23 verifiedSubmit = (e) => { 24 this.setState({ loading: true }); 25 e.preventDefault(); 26 this.props.form.validateFields((err, values) => { 27 if (!this.state.yztime == 0) { 28 this.count(); 29 } 30 let verify = { phone: values.accountname, gettype: 1 } 31 this.props.dispatch({ type: '***/***', payload: { verify } }); 32 }); 33 } 34 35 render() { 36 const { form: { getFieldDecorator } } = this.props; 37 return ( 38 <Form> 39 <FormItem> 40 {getFieldDecorator('yzm', { 41 rules: [{ required: false, message: '请输入验证码!' }], 42 })(<Input placeholder="请输入验证码" /> 43 )} 44 <Button loading={this.state.loading} htmlType="submit" onClick={this.verifiedSubmit}> 45 {this.state.loading ? this.state.yztime + '秒' : '发送验证'} 46 </Button> 47 </FormItem> 48 </Form> 49 ); 50 } 51 52
代码就这样了!
小生的第一篇博客,如有不足之处,还望多多指教