import React, { Component } from 'react'; import './veri-code-input.scss' import { http, api } from '@/utils'; import { Toast } from "antd-mobile"; import classnames from 'classnames' import Input from '../Input' class VeriCodeInput extends Component { count = 10 state = { counting: false, count: this.count, isFirst: true } timer = null countDown = () => { let {count} = this.state if (!this.state.isFirst) { Toast.info('请重新进行滑块验证',2,null,false) this.props.instance.refresh() this.setState({ isFirst: true }) return } if (!this.state.counting) { if (!this.sendCode()) { return } this.setState({count: count--, counting: true}) this.timer = setInterval(() => { if (count <= 0) { clearInterval(this.timer) this.setState({counting: false, count: this.count}) return } this.setState({count: count--}) }, 1000) } } sendCode = () => { if (!this.validate()) return const {action, tel, challenge} = this.props http.post(`${api['passport-api']}/quick_sms`, { phone_num: tel, action: action || 'login', challenge }).then(res => { if (res.data.errno === 0) { Toast.info('验证码发送成功', 2, null, false) } else { Toast.info(res.data.msg, 2, null, false) } this.setState({ isFirst: false }) }) return true } validate = () => { const {tel, challenge} = this.props if (!tel) { Toast.info('手机号码不能为空', 2, null, false) return false } if (!challenge) { Toast.info('请进行滑块验证', 2, null, false) return false } return true } render() { let {type = 'number', className, ...rest} = this.props return ( <Input type={type} wrapperClass={className} {...rest} > <button type='button' className={classnames('verify', {active: !this.state.counting})} onClick={this.countDown}> { this.state.counting ? (`重新发送${this.state.count}s`) : '发送验证码' } </button> </Input> ); } } export default VeriCodeInput;