使用react-native 开发app时制作秒表功能,可用react-native-stopwatch-timer插件
效果图如下:
开发步骤:
1、安装依赖:
npm install react-native-stopwatch-timer
引用:
import { Stopwatch, Timer } from 'react-native-stopwatch-timer'
编辑StopwatchTimer.js文件
import React, { Component } from 'react';
import { AppRegistry, StyleSheet,Text,View, TouchableHighlight } from 'react-native';
import { Stopwatch, Timer } from 'react-native-stopwatch-timer';
class StopwatchTimer extends Component {
constructor(props) {
super(props);
this.state = {
timerStart: false,
stopwatchStart: false,
totalDuration: 90000,
timerReset: false,
stopwatchReset: false,
};
this.toggleTimer = this.toggleTimer.bind(this);
this.resetTimer = this.resetTimer.bind(this);
this.toggleStopwatch = this.toggleStopwatch.bind(this);
this.resetStopwatch = this.resetStopwatch.bind(this);
}
toggleTimer() {
this.setState({timerStart: !this.state.timerStart, timerReset: false});
}
resetTimer() {
this.setState({timerStart: false, timerReset: true});
}
toggleStopwatch() {
this.setState({stopwatchStart: !this.state.stopwatchStart, stopwatchReset: false});
}
resetStopwatch() {
this.setState({stopwatchStart: false, stopwatchReset: true});
}
getFormattedTime(time) {
this.currentTime = time;
};
render() {
return (
<View>
<Stopwatch laps msecs start={this.state.stopwatchStart}
reset={this.state.stopwatchReset}
options={options}
getTime={this.getFormattedTime} />
<TouchableHighlight onPress={this.toggleStopwatch}>
<Text style={{fontSize: 30}}>{!this.state.stopwatchStart ? "Start" : "Stop"}</Text>
</TouchableHighlight>
<TouchableHighlight onPress={this.resetStopwatch}>
<Text style={{fontSize: 30}}>Reset</Text>
</TouchableHighlight>
<Timer totalDuration={this.state.totalDuration} msecs start={this.state.timerStart}
reset={this.state.timerReset}
options={options}
handleFinish={handleTimerComplete}
getTime={this.getFormattedTime} />
<TouchableHighlight onPress={this.toggleTimer}>
<Text style={{fontSize: 30}}>{!this.state.timerStart ? "Start" : "Stop"}</Text>
</TouchableHighlight>
<TouchableHighlight onPress={this.resetTimer}>
<Text style={{fontSize: 30}}>Reset</Text>
</TouchableHighlight>
</View>
);
}
}
const handleTimerComplete = () => alert("custom completion function");
const options = {
container: {
backgroundColor: '#000',
padding: 5,
borderRadius: 5,
width: 220,
},
text: {
fontSize: 30,
color: '#FFF',
marginLeft: 7,
}
};
export default StopwatchTimer;
小伙伴们感觉有帮助的话希望点个赞哟,如果有问题或疑问欢迎大家评论区留言,看到后第一时间回复。