語錄:作為一個真正的程序員,首先應該尊重編程,熱愛你所寫下的程序,他是你的伙伴,而不是工具
目標:開發(fā)一款倒計時的插件。用于短信驗證碼倒計時,用于商城秒殺倒計時等等。

最終結(jié)果展示
版本:
"dependencies": {
"react": "16.0.0-alpha.12",
"react-native": "0.47.1"
},
//代碼直接拷貝可用。
思路:
分三個步驟:
1.計時開始,處理秒:
如果秒為0,則請求分鐘函數(shù)。如果分鐘返回的是0,則終止計時。
2.分鐘處理:
如果分鐘為0,則從小時哪里請求,如果請求到0,說明時間計時結(jié)束,返回0;
如果分鐘為0,從小時哪里請求到1,說明請求成功,將分鐘設(shè)置為59,返回1;
如果分鐘不為0,則分鐘自身-1。
3.小時處理:
如果小時不為0,則自身-1,返回1;
如果小時為0,直接返回0。
代碼實現(xiàn):
/**
* 開發(fā)者:杜二紅<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>
);
}
// 實現(xiàn)在這里借小時
get_hour() {
var hu=this.state.hour; //獲取分鐘
if (hu>0) { //分鐘不為0,則直接借走1分鐘
hu--; //分鐘減一
this.setState({hour:hu}); //更改分鐘狀態(tài)
return 1; //借走一分鐘
}
else if (hu==0) { //分鐘為0,從小時哪里借
this.setState({hour:'00'}); //更改分鐘狀態(tài)
return 0;
}
}
// 實現(xiàn)在這里借分鐘
get_minutes() {
var mt=this.state.minutes; //獲取分鐘
if (mt>0) { //分鐘不為0,則直接借走1分鐘
mt--; //分鐘減一
this.setState({minutes:mt}); //更改分鐘狀態(tài)
return 1; //借走一分鐘
}
else if (mt==0) { //分鐘為0,從小時哪里借
var get_hu=this.get_hour();
if (get_hu==1) { //借到了
this.setState({minutes:59}); //更改分鐘狀態(tài)
return 1;
}
else{
this.setState({minutes:'00'}); //沒借到,更改分鐘狀態(tài)
return 0;
}
}
}
// 計時函數(shù)
countTime(){
this._timer=setInterval(()=>{
var ct=this.state.seconds; //獲取秒
if (ct>0) { //如果秒大于0,則執(zhí)行減1
ct--;
this.setState({seconds:ct}); //更改秒的狀態(tài)
}
else if (ct==0) { // 秒為0,去借分鐘
var get_mt=this.get_minutes();
if (get_mt==1) { //借分鐘成功
ct=59;
this.setState({seconds:ct}); //將秒設(shè)置為59
}
else if (get_mt==0) { //沒借到分鐘,說明計時結(jié)束
this._timer&&clearInterval(this._timer);
}
}
},1000);
}
}
AppRegistry.registerComponent('Login', () => Login);