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
代碼就這樣了!
小生的第一篇博客,如有不足之處,還望多多指教
