[英]How to restart timer at the onPress in react native
我为计时器做了一个小功能,计时器将从10
开始倒计时。 当它达到0
时,计时器将隐藏,并在该位置出现一个重新启动按钮。 到目前为止,我能够做到。
但是我想在倒计时完成后出现Restart
时重新启动计时器。
下面是代码:
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>
如您所见,倒计时完成时会出现Restart
,但是当我单击Restart
时,它显示错误: Cannot read property 'setState' of undefined
。
绑定您的方法 当您调用restartButton()
function 时,它会在上下文中返回this
的值,在本例中为null
。
由于 App 的this
上下文是restartButton()
应该使用的上下文,因此我们必须在构造函数中对其使用.bind()
方法。
constructor(props) {
super(props);
this.state = {
timer: 10,
displayButton: 'none',
displayTime: 'flex'
};
this.restartButton= this.restartButton.bind(this);
}
另一种方法(箭头功能)是如果您不想绑定 function
restartButton =()=> {
this.setState({
displayTime: "flex",
displayButton: "none",
timer: 30,
})
}
在 class 组件中,我们不能直接调用使用此关键字作为类内组件的方法。此关键字指的是它调用的 object,因为这里它从可触摸的不透明度中调用,可能指的是您正在接收的可触摸 ZA8CFDE6331BD59EB2AC96F89111111C4 this.setState 的错误不是 function 因为没有 function 例如 setState in touchable。 所以你必须将方法与组件绑定来更新 state 或者你可以简单地调用 function 如下代码
onPress={() => this.restartButton()}
要绑定 function 您可以在 class 构造函数中使用以下代码
this.restartButton= this.restartButton.bind(this);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.