大佬教程收集整理的这篇文章主要介绍了React-Native中使用验证码倒计时的按钮实例代码,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
开发过程中有获取手机验证码的场景,这时候有这样的要求:
1,点击“获取验证码”的按钮,发起获取验证码的网络请求,同时按钮置为不可用
2,如果网络请求成功,按钮继续不可用,但按钮上文本改为倒计时((*s)后重新获取)
3,如果网络请求失败,按钮置为可用
4,倒计时结束,按钮可用
直接上代码
源码
import React,{PropTypes} from 'react'; import {View,Text,TouchabLeopacity} from 'react-native'; export default class TimerButton extends React.Component { constructor(props) { super(props) this.state = { timerCount: this.props.timerCount || 90,timertitle: this.props.timertitle || '获取验证码',counTing: false,selfEnable: true,}; this._shouldStartCountTing = this._shouldStartCountTing.bind(this) this._countDownAction = this._countDownAction.bind(this) } static propTypes = { style: PropTypes.object,textStyle: Text.propTypes.style,onClick: PropTypes.func,disableColor: PropTypes.String,timertitle: PropTypes.String,enable: React.PropTypes.oneOfType([React.PropTypes.bool,React.PropTypes.number]) }; _countDownAction(){ const codeTime = this.state.timerCount; this.interval = seTinterval(() =>{ const timer = this.state.timerCount - 1 if(timer===0){ this.interval&&clearInterval(this.interval); this.setState({ timerCount: codeTime,selfEnable: true }) }else{ console.log("---- timer ",timer); this.setState({ timerCount:timer,timertitle: `重新获取(${timer}s)`,}) } },1000) } _shouldStartCountTing(shouldStart){ if (this.state.counTing) {return} if (shouldStart) { this._countDownAction() this.setState({CounTing: true,selfEnable:falsE}) }else{ this.setState({selfEnable:truE}) } } componentWillUnmount(){ clearInterval(this.interval) } render(){ const {onClick,style,textStyle,enable,disableColor} = this.props const {CounTing,timertitle,selfEnablE} = this.state return ( <TouchabLeopacity activeOpacity={CounTing ? 1 : 0.8} onPress={()=>{ if (!counTing && enable && selfEnablE) { this.setState({selfEnable:falsE}) this.props.onClick(this._shouldStartCountTing) }; }}> <View style={[{width:100,height:44,flex:1,justifyContent:'center',alignItems:'center'},style]}> <Text style={[{fontSize: 16},{Color: ((!counTing && enable && selfEnablE) ? textStyle.color : disableColor || 'gray')}]}>{timertitlE}</Text> </View> </TouchabLeopacity> ) } }
使用
<TimerButton enable={phonenumber.length} style={{width: 110,marginRight: 10}} textStyle={{Color: StaticColor.COLOR_MAIN}} timerCount={10} onClick={(shouldStartCountTing)=>{ this._requestSMSCode(shouldStartCountTing) }}/>
onClick
:触发后按钮selfEnable
会立即被置为false
onClick
中的一系列逻辑处理之后需要调用回调函数结束倒计时shouldStartCountTing
:回调函数,接受一个Bool
类型的参数
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程小技巧。
以上是大佬教程为你收集整理的React-Native中使用验证码倒计时的按钮实例代码全部内容,希望文章能够帮你解决React-Native中使用验证码倒计时的按钮实例代码所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。