由于最近刚开始认真的搞rn,可能有一些封装的不是最佳实践,还是希望大家多提意见,和大家一起进步吧。本文介绍了reactnative短信验证码倒计时控件,分享给大家
功能
根据项目的需要,需要写一个自定义的控件,实现如下功能:
其实说了这么多,就是个最普通的验证码的功能。。。
效果
效果图如下:(录的图片比较一般,对付着看吧)
实现原理
自己封装了个控件,它内部含有一个text控件,然后我们又写了一个timer,然后负责倒计时,然后每次都需要判断一下是否继续,然后加了一个flag字段,判断是否接受下次点击事件,当倒计时结束之后还需要将初始状态重置回去即可。
代码
控件代码
import react, {component } from 'react'; import { stylesheet, text, view, image, textinput, touchablehighlight, statusbar, alert, appregistry } from 'react-native'; import linkrow from '../components/linkrow'; import cstyles from '../styles/commonstyle'; import axios from 'axios'; class mycounttime extends component { constructor(props) { super(props); let timeleft = this.props.timeleft > 0 ? this.props.timeleft : 5; let width = this.props.width || 100; let height = this.props.height || 50; let color = this.props.color || '#42a5f5'; let fontsize = this.props.fontsize || 30; let fontweight = this.props.fontweight || '600'; let bordercolor = this.props.bordercolor || '#42a5f5'; let borderwidth = this.props.borderwidth || 1; let borderradius = this.props.borderradius || 4; let backgroundcolor = this.props.backgroundcolor || '#42a5f5'; let begin = 0; let press = this.props.press; this.afterend = this.props.afterend || this._afterend; this.style = this.props.style; this.state = { timeleft: timeleft, begin: begin }; this.counttextstyle = { textalign: 'center', color: '#42a5f5', fontsize: fontsize, fontweight: fontweight }; this.countviewstyle = { backgroundcolor: backgroundcolor, alignitems: 'center', bordercolor: bordercolor, borderwidth: borderwidth, borderradius: borderradius, width: width, height: height } } countdownfn(timeleft, callback, begin) { if (timeleft > 0) { this.state.begin = 1; console.log("===lin===>"); let that = this; let interval = setinterval(function () { if (that.state.timeleft < 1) { clearinterval(interval); callback(that) } else { let totaltime = that.state.timeleft; that.setstate({ timeleft: totaltime - 1 }) } }, 1000) } } _begincountdown() { if (this.state.begin === 1){ return; } let time = this.state.timeleft; console.log("===lin===> time " + time); let afterend = this.afterend; let begin = this.state.begin; console.log("===lin===> start " + begin); this.countdownfn(time, afterend, begin) } _afterend(that) { console.log('------------time over'); that.setstate({ begin : 0, timeleft : 5, }) } componentdidmount() { } render() { return ( <view style={{position:'absolute',top:13,right:43,height:30}}> <text onpress={this._begincountdown.bind(this)} style={{color: '#42a5f5', fontsize: 17,height:40 , zindex:999}}> { this.state.begin === 0 ? '点击获取验证码' : this.state.timeleft} </text> </view> ) } }
应用代码
<mycounttime timeleft={5}> </mycounttime>
当然这只是,最简单的应用的代码,我们还提供了很多的自定义的属性,大家可以根据自己项目的需要,去调节这些参数。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。
如对本文有疑问, 点击进行留言回复!!
轻松解决 org.apache.taglibs.standard.tlv.JstlCoreTLV 困惑
vert实践五——Json?Protocol Buffer?FlatBuffers?
[基于tensorflow的人脸检测] 基于神经网络的人脸检测8——验证训练好的神经网络
selenium + ajax抓取英雄联盟全部英雄的详细信息及多线程保存全部皮肤图片到本地
网友评论