在反应本机中重新启动倒数计时器



在倒数计时器上工作,我希望能够在按下按钮时重新启动倒计时,但是,我认为该按钮不起作用,因为我没有得到任何反馈。 有人可以指出我正确的方向吗? 下面是我试图实现的目标的精简示例代码。

export default class Example extends Component {
constructor(props) {
super(props);
this.state = {
timer: 10,
timesup: false,
timing: true,
showWelcome: true,
};
}
componentDidMount() {
this.clockCall = setInterval(() => {
this.decrementClock();
}, 1000);
}
startTimer = () => {
this.setState({
timing: true,
timer: 30,
showWelcome: false
})
}

decrementClock = () => {
this.setState((prevstate) => ({
timer: prevstate.timer - 1
}), () => {
if (this.state.timer === 0) {
clearInterval(this.clockCall)
this.setState({
timesup: true,
timing: false,
showWelcome: false,
})
}
})
}

componentWillUnmount() {
clearInterval(this.clockCall);
}

render() {
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
{this.state.timesup && (
<Text style={{fontSize: 18, color: '#000'}}>
Time up
</Text>)}

{this.state.timing && (
<Text style={{fontSize: 18, color: '#000'}}>
{this.state.timer}
</Text>)}
{this.state.showWelcome && (
<Text style={{ fontSize: 20 }}>Welcome</Text>
)}
<Button Onpress={this.startTimer.bind(this)} title='play' />
</View>
)
}
}

我相信你在寻找的是onPress,而不是Onpress。此外,如果您正在使用:

startTimer = () => ...

用:

this.startTimer.bind

没有效果,因为该方法已由箭头函数绑定到。然后,您可以简单地使用:

onPress={this.startTimer}

最新更新