【发布时间】:2018-08-26 02:37:27
【问题描述】:
我正在尝试制作一个简单的番茄钟计时器。我需要让暂停和停止按钮工作。 我定义了一个名为“Timer”的单独组件并添加了两个按钮:“Pause”和“Stop”,这显然会影响 Timer 的状态。
当各个按钮被按下时如何调用Timer的停止和暂停方法?
我知道我可以通过在 Timer 类中简单地包含按钮来做到这一点,但我想学习如何在未来实现类似的功能,并且我想保持 Timer 的计数器部分独立。
代码如下:
import React from 'react'
import { Text, View, Button, StyleSheet } from 'react-native';
import { Constants } from 'expo';
class Timer extends React.Component{
constructor (props){
super(props)
this.state = {
minutes: props.minutes,
seconds: props.seconds,
count: 0,
}
}
dec = () => {
this.setState(previousState => {
if (previousState.seconds==0){
return {
minutes: previousState.minutes-1,
seconds: 59,
count: previousState.count+1,
}
}
else{
return{
minutes: previousState.minutes,
seconds: previousState.seconds-1,
count: previousState.count+1,
}
}
});
}
componentDidMount (){
setInterval(this.dec,1000);
}
render (){
return(
<View style = {{flexDirection: 'row'}}>
<Text style = {styles.timerCount}> {this.state.minutes}</Text>
<Text style = {styles.timerCount}>:</Text>
<Text style = {styles.timerCount}> {this.state.seconds} </Text>
</View>
)
}
stop (){
console.log('stop')
}
pause (){
console.log('pause')
}
}
export default class App extends React.Component {
stop (){
console.log('stop')
}
render() {
return(
<View style={styles.container}>
<Timer style = {styles.timer} minutes={25} seconds = {0}/>
<View style = {styles.buttonContainer}>
<Button title = 'Pause' style = {styles.timerButton} color = 'white' onPress = {()=>{console.log("call the timer's pause method here")}}/>
<Button title = 'Stop' style = {styles.timerButton} color = 'white' onPress = {()=>{console.log("call the timer's stop method here")}}/>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
buttonContainer: {
flexDirection: 'row',
},
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
paddingTop: 50,
backgroundColor: '#EC3D40',
},
timer: {
backgroundColor: '#EC3D40',
paddingTop: 50,
},
timerCount: {
fontSize: 48,
color: 'white',
backgroundColor: '#EC3D40',
paddingTop: 10,
paddingBottom: 10,
},
timerButton:{
borderColor: 'white',
backgroundColor: 'transparent',
}
});
【问题讨论】:
-
您需要提升状态。可能你需要制作一个包含 Timer、Button 和 state 的组件
标签: javascript reactjs react-native