版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
最近做的东西需要倒计时验证码,但是taro-UI里面没有,然后就只能手写。可能用taro的人还不多,很多组件还不是很完善,但是总体说来taro还是很不错的。那么下面我们来看倒计时怎么写,先贴效果图:
现在看到了样式的效果,那么代码是怎么样的呢?
1、先看数据,也就是state中的内容 phone_no是号码,icode是验证码,code_ts是按钮中是提示内容,show_btn是否展示获取验证码按钮,
toast一个提示框控制,count倒计时秒数
this.state = {
phone_no: '',
icode: '',
code_ts: '获取验证码',
show_btn: true,
toast: false,
count: 60
}
2、然后是结构中的内容,样式应该不用了吧
<View className='phone_box_mid'>
<AtInput
className='input_main'
name='phone'
border = { false }
type='phone'
placeholder='请输入11位手机号码'
value = { this.state.phone_no }
onChange = { this.handleChange.bind(this) }
/>
</View>
<View className='phone_box_right'>
{
this.state.show_btn ?
<AtButton size='small' type='secondary' circle = { true } onClick = { this.getCode.bind(this) }>获取验证码</AtButton>
: <AtButton className='disbtn' disabled = { true } size='small' type='secondary' circle = { true }> { this.state.code_ts }</AtButton>
}
</View>
3、然后就是函数的处理了,其实也十分简单,话不多说,代码奉上
getCode () {
if(this.state.phone_no === '' || !(/^1[3456789]\d{9}$/.test(this.state.phone_no))){
// 这里验证一下号码格式是否正确,为空或者不正常都提示一下,然后激活提示控件true,其他的框架提示控件同理
console.log('提示')
this.setState({
toast: true
})
// 因为提示后一直为true的话输入内容好像也会激活setstate,所以提示后我会改成false
setTimeout(() => {
this.setState({
toast: false
})
},2000)
} else{
let count = this.state.count
// 这里写一个定时器就可以去更新灰色按钮的内容而且show_btn是false时会出现灰色按钮,当倒计时结束又变成可以触发的按钮
const timer = setInterval(() => {
this.setState({
count: (count--),
show_btn: false,
code_ts: count +'S重发'
}, () => {
if (count === 0) {
clearInterval(timer)
this.setState({
show_btn: true ,
count: 60,
code_ts: '获取验证码'
})
}
})
}, 1000)
}
}
总结:就是这些了,是不是很简单呢!