I have made a small functionality for timer, where a timer will countdown from 10
. When it reaches 0
, the timer will hide, and a restart button will come at that place. Till this far, I am able to do it.
But I wanted to restart the timer when Restart
appears after countdown is completed.
Below is the code:
constructor(props) {
super(props);
this.state = {
timer: 10,
displayButton: 'none',
displayTime: 'flex'
};
}
componentDidMount() {
this.clockCall = setInterval(() => {
this.decrementClock();
}, 1000);
}
decrementClock = () => {
this.setState(
(prevState) => ({timer: prevState.timer - 1}),
() => {
if (this.state.timer === 0) {
this.setState({
displayTime: "none",
displayButton: "flex"
})
}
},
);
};
restartButton() {
this.setState({
displayTime: "flex",
displayButton: "none",
timer: 30,
})
}
<Text style={{display: this.state.displayTime}}>{this.state.timer}</Text>
<TouchableOpacity onPress={this.restartButton}>
<Text style={{display:this.state.displayButton}}>Restart</Text>
</TouchableOpacity>
As you can see, Restart
appears when countdown is finished, But when I click on Restart
it is showing me error: Cannot read property 'setState' of undefined
.
question from:
https://stackoverflow.com/questions/65843860/how-to-restart-timer-at-the-onpress-in-react-native 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…