javascript - 如何在此计时器中添加暂停功能?反应原生
问题描述
//导入不同的文件
import * as React from 'react';
import { Text, View, StyleSheet,Button } from 'react-native';
import { Constants } from 'expo';
import AssetExample from './components/AssetExample';
//创建样式表
const styles = StyleSheet.create({
appContainer : {
flex :1 ,
alignItems : 'center',
justifyContent : 'center',
},
text : {
fontSize : 40 ,
}
})
export class App extends React.Component{
//在这里创建一个构造函数并设置状态
constructor(props)
{
super(props)
this.state = ({
minutes : 0,
seconds : 4,
pause : false,
})
}
//定时器开始功能分钟,如果它减少1然后自动设置秒状态。
startTimer = () => {
this.setState({
minutes : this.state.minutes - 1,
seconds : 4
})
}
//Timer2 每瞬间将秒数减 1。
startTimer2 = () => {
this.setState({
seconds : this.state.seconds - 1
})
console.log(this.props.toggle)
}
//这里设置两个定时器的时间间隔。
componentDidMount = () => {
this.interval = setInterval(this.startTimer , 5000)
this.interval2 = setInterval(this.startTimer2 , 1000)
}
//如果分钟数低于零,则不更新。
shouldComponentUpdate = (nextProps , nextState) => {
if(nextState.minutes >= 0 )
{
return(
true
)
}
// 如果它低于它,只需清除间隔
else {
clearInterval(this.interval)
clearInterval(this.interval2)
}
}
//组件将被卸载
componentWillUnmount = () => {
clearInterval(this.interval)
clearInterval(this.interval2)
}
//切换暂停时间
pauseTimer = ()=> {
this.setState({
pause : !this.state.pause
})
}
//一个渲染函数
render() {
if(this.state.minutes === 0 && this.state.seconds === 0)
{
return(
<View style = {styles.appContainer}>
<Text style ={styles.text}>
Break is over
</Text>
</View>
)
}
else if (this.state.pause === false)
{
return (
<View style = {styles.appContainer}>
<Text style ={styles.text}>
{this.state.minutes} : {this.state.seconds}
</Text>
<Button title = "Pause" onPress = {()=>this.pauseTimer()}
/>
</View>
)
}
else {
return (
<View style = {styles.appContainer}>
<Text style ={styles.text}>
{this.state.minutes} : {this.state.seconds}
Paused
</Text>
<Button title = "Start again" onPress = {()=>this.pauseTimer()}/>
</View>
)
}
}
解决方案
我在纯 javascript 中创建了一个简短的片段,展示了如何停止和重新启动间隔。
它还显示了如何使用一个计数器计算分钟和秒。
抱歉,我还没有在 React 中实现这个!你仍然需要在你的 React 模板中实现它,但是setInterval
逻辑和秒计数器应该是一样的。
let id;
let paused = true;
let seconds = 0;
let btn = document.querySelector("#btn");
btn.addEventListener("click", ()=>{
toggleTimer();
});
function startTimer(){
id = setInterval(()=>{
seconds++;
let minutes = Math.floor(seconds/60);
let sec = seconds%60;
console.log(minutes + " : " + sec);
}, 100);
}
function stopTimer(){
clearInterval(id);
}
function toggleTimer(){
console.log(paused);
if(paused){
paused = false;
startTimer();
} else {
paused = true;
stopTimer();
}
}
推荐阅读
- scala - 如何在 Cats IO 效果中测量经过的时间?
- c - 创建控制台管道而不是文件管道
- java - 将 Double 与从方法计算的 Double 值相等会导致 0.0?可能是什么问题呢?
- ios - 如何在 Xcode 中使用 CMake 添加 Copy Bundle Resources 阶段?
- c# - asp.net核心项目中的不断错误
- php - PHPMailer 使用 oauth2 gmail SMTP - 如何防止电子邮件进入已发送文件夹?
- powershell - 如果进程冻结,则终止进程
- python - 遍历多个 Pandas 数据帧时删除行
- vb.net - 如何将一个按钮单击生成的变量传递给另一个按钮单击的函数?
- java - 独立消费者(SpringJMS)在 ActiveMQ 上创建了另一个队列