React-Native中使用验证码倒计时的按钮

作者: 尹_路人 | 来源:发表于2017-04-06 13:48 被阅读4310次

开发过程中有获取手机验证码的场景,这时候有这样的要求:
1,点击“获取验证码”的按钮,发起获取验证码的网络请求,同时按钮置为不可用
2,如果网络请求成功,按钮继续不可用,但按钮上文本改为倒计时((*s)后重新获取)
3,如果网络请求失败,按钮置为可用
4,倒计时结束,按钮可用

直接上代码

源码

"use strict";

import React,{PropTypes} from 'react';
import {
    View,
    Text,
    TouchableOpacity,
    ViewPropTypes
} from 'react-native';
export default class CountDownButton extends React.Component {
    constructor(props) {
      super(props)
        this.state = {
            timerCount: this.props.timerCount || 60,
            timerTitle: this.props.timerTitle || '获取验证码',
            counting: false,
            selfEnable: true,
        };
        this._shouldStartCountting = this._shouldStartCountting.bind(this)
        this._countDownAction = this._countDownAction.bind(this)
    }
    static propTypes = {
      style: ViewPropTypes.style,
      textStyle: Text.propTypes.style,
      onClick: PropTypes.func,
      disableColor: PropTypes.string,
      timerTitle: PropTypes.string,
      enable: PropTypes.oneOfType([PropTypes.bool,PropTypes.number]),
      timerEnd: PropTypes.func
    };

    _countDownAction(){
        const codeTime = this.state.timerCount;
        const now = Date.now()
        const overTimeStamp = now + codeTime * 1000 + 100/*过期时间戳(毫秒) +100 毫秒容错*/
        this.interval = setInterval(() =>{
            /* 切换到后台不受影响*/
            const nowStamp = Date.now()
            if (nowStamp >= overTimeStamp) {
                /* 倒计时结束*/
                this.interval&&clearInterval(this.interval);
                this.setState({
                    timerCount: codeTime,
                    timerTitle: this.props.timerTitle || '获取验证码',
                    counting: false,
                    selfEnable: true
                })
                if (this.props.timerEnd) {
                    this.props.timerEnd()
                };
            }else{
                const leftTime = parseInt((overTimeStamp - nowStamp)/1000, 10)
                this.setState({
                    timerCount: leftTime,
                    timerTitle: `重新获取(${leftTime}s)`,
                })
            }
            /* 切换到后台 timer 停止计时 */
            /*
            const timer = this.state.timerCount - 1
            if(timer===0){
                this.interval&&clearInterval(this.interval);
                this.setState({
                    timerCount: codeTime,
                    timerTitle: this.props.timerTitle || '获取验证码',
                    counting: false,
                    selfEnable: true
                })
            }else{
                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:120, height:44,justifyContent:'center',alignItems:'center'},style]}>
                    <Text style={[{fontSize: 16},textStyle,{color: ((!counting && enable && selfEnable) ? (textStyle ? textStyle.color : 'blue') : disableColor || 'gray')}]}>{timerTitle}</Text>
                </View>
            </TouchableOpacity>
        )
    }
}   

使用

gitHub
点击下载源文件

import CountDownButton from './countDownButton.js'
  ...

< CountDownButton enable={phoneNumber.length}
    style={{width: 110,marginRight: 10}}
    textStyle={{color: 'blue'}}
    timerCount={10}
    timerTitle={'点击获取验证码'}
    timerActiveTitle={['请在(','s)后重试']}
    onClick={(shouldStartCountting)=>{
      // shouldStartCountting是一个回调函数,根据调用接口的情况在适当的时候调用它来决定是否开始倒计时
      //随机模拟发送验证码成功或失败
      const requestSucc = Math.random() + 0.5 > 1; 
      shouldStartCounting(requestSucc)
    }}/>
  • shouldStartCountting:回调函数,接受一个Bool类型的参数
    • shouldStartCountting(true),开始倒计,但按钮仍不可点击,直到倒计时结束
    • shouldStartCountting(false), 按钮恢复可点击状态,但不会开始倒计时
props type default value mark
onClick func - 点击后触发,同时将按钮置为不可用,配合shouldStartCountting 使用
timerCount number 60 倒计时时长
shouldStartCountting func - 决定是否开始倒计时的回调函数,参数类型Bool
style View style - -
textStyle Text style - -
disableColor string gray 按钮不可用状态下的颜色
enable bool false 按钮是否可用(比如用户输入合法手机号时可用,否则不可用)
timerEnd func - 倒计时结束的回调函数
timerActiveTitle array ['重新获取(', 's)'] 倒计时的数字会插在数组第一项之后,如:['请在', '秒后重新获取'],显示为【请在60秒后重新获取】

---

更新: 切换到后台验证码倒计时跑秒不受影响

---

17/07/25 更新:
1、更换贴图
2、发布到npm
支持通过 npm 命令安装和使用

  npm i react-native-smscode-count-down --save

更新
添加属性timerActiveTitle(Array)

具体用法请移步 GitHub

版权印为您的作品印上版权93826917

相关文章

网友评论

  • AINIDEXIN:报错undefined not an object(evaluating '_react.PropTypes.func'),楼主什么原因啊?
    AINIDEXIN:@尹_路人 在react-native上使用没问题吧?
    尹_路人:你的React版本是多少,是否有引用'prop-types', 如果没有,装一下这个依赖: https://www.npmjs.com/package/prop-types
  • haisonLIN:案例里shouldStartCounting(requestSucc)的shouldStartCounting少了个t😬
  • GorgeousXie:楼主,刚测试的时候发现了一个bug,倒计时的有些数字会漏掉。显示的倒计时可能为:
    59,58,57,56,55,54,53,51,50....
    谢谢回复~~~😊
  • 香蕉大熊猫:切换到后台 timer 停止计时,这个功能怎么实现的? RN有监听这个的接口么?
  • a974cdd06836:您好,要做一个像购物车选中商品有个勾勾出来,再点击就没有了,这个功能要怎么实现啊
  • Rocky_92d5:github上的源码,跟你贴的图,对不上。
    尹_路人:@Rocky_92d5 我也没说贴图跟Demo完全对的上啊:relieved:
  • 5ec1da87f063:如果退到后台,计时器还会走吗?
    5ec1da87f063:@尹_路人 感谢大神
    尹_路人:@5ec1da87f063 文章已更新,切换到后台,计时不受影响
    尹_路人:如果需要退到后台继续执行的话需要改一下实现
    思路如下:
    当前的时间戳是 T1 = 1000,倒计时 60秒,那么结束时的时间戳就是T2 = 1060,在timer内部,比较最新的时间戳和结束时间戳,一旦T2 < T1则意味着倒计时结束

    这样就不受退到后台影响了
  • 8566dc2f3614:楼主你好,我照着上面的用了之后抛错:RawText" "must be wrapped in an explicit<Text>component, 我也不懂为什么唉:joy:
  • 陈斌彬:我想问,我添加了插件之后。render之后没有显示TimerButton出来,是还需要别的配置吗?
    0baa9561da80:@陈斌彬 我的也没显示TimerButton
    陈斌彬:@尹_路人 好的。可以运行有效果了。thanks
    尹_路人:把上文中的“源码”部分另存为一个js文件,在使用的地方引入,参照上文中“使用”部分即可,不需要其他配置
  • 果子熊:厉害了
  • 凌霄_:支持一下

本文标题:React-Native中使用验证码倒计时的按钮

本文链接:https://www.haomeiwen.com/subject/xxqqattx.html