语录:作为一个真正的程序员,首先应该尊重编程,热爱你所写下的程序,他是你的伙伴,而不是工具
目标:开发一款倒计时的插件。用于短信验证码倒计时,用于商城秒杀倒计时等等。
最终结果展示
版本:
"dependencies": {
"react": "16.0.0-alpha.12",
"react-native": "0.47.1"
},
//代码直接拷贝可用。
思路:
分三个步骤:
1.计时开始,处理秒:
如果秒为0,则请求分钟函数。如果分钟返回的是0,则终止计时。
2.分钟处理:
如果分钟为0,则从小时哪里请求,如果请求到0,说明时间计时结束,返回0;
如果分钟为0,从小时哪里请求到1,说明请求成功,将分钟设置为59,返回1;
如果分钟不为0,则分钟自身-1。
3.小时处理:
如果小时不为0,则自身-1,返回1;
如果小时为0,直接返回0。
代码实现:
/**
* 开发者:杜二红<1186969412@qq.com>
* http://www.uminicmf.com
* QQ:1186969412 微信:uminicmf
*/
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
View,
Text,
Button
} from 'react-native';
export default class Login extends Component {
constructor(props){
super(props);
this.state={
hour:'1',
minutes:'0',
seconds:'2',
}
// countTime();
}
render() {
return (
<View style={{flex:1,justifyContent:'center',alignItems:'center'}}>
<Text style={{fontSize:22}}>{this.state.hour}:{this.state.minutes}:{this.state.seconds}</Text>
<Button
onPress={this.countTime.bind(this)}
title="开始计时"
color="#841584"
accessibilityLabel="开始计时"
/>
</View>
);
}
// 实现在这里借小时
get_hour() {
var hu=this.state.hour; //获取分钟
if (hu>0) { //分钟不为0,则直接借走1分钟
hu--; //分钟减一
this.setState({hour:hu}); //更改分钟状态
return 1; //借走一分钟
}
else if (hu==0) { //分钟为0,从小时哪里借
this.setState({hour:'00'}); //更改分钟状态
return 0;
}
}
// 实现在这里借分钟
get_minutes() {
var mt=this.state.minutes; //获取分钟
if (mt>0) { //分钟不为0,则直接借走1分钟
mt--; //分钟减一
this.setState({minutes:mt}); //更改分钟状态
return 1; //借走一分钟
}
else if (mt==0) { //分钟为0,从小时哪里借
var get_hu=this.get_hour();
if (get_hu==1) { //借到了
this.setState({minutes:59}); //更改分钟状态
return 1;
}
else{
this.setState({minutes:'00'}); //没借到,更改分钟状态
return 0;
}
}
}
// 计时函数
countTime(){
this._timer=setInterval(()=>{
var ct=this.state.seconds; //获取秒
if (ct>0) { //如果秒大于0,则执行减1
ct--;
this.setState({seconds:ct}); //更改秒的状态
}
else if (ct==0) { // 秒为0,去借分钟
var get_mt=this.get_minutes();
if (get_mt==1) { //借分钟成功
ct=59;
this.setState({seconds:ct}); //将秒设置为59
}
else if (get_mt==0) { //没借到分钟,说明计时结束
this._timer&&clearInterval(this._timer);
}
}
},1000);
}
}
AppRegistry.registerComponent('Login', () => Login);