javascript - 如何在反应原生的onPress上重新启动计时器
问题描述
我为计时器做了一个小功能,计时器将从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
。
解决方案
在类组件中,我们不能直接调用使用 this 关键字作为类内组件的方法 this 关键字指的是它调用的对象,因为这里它调用 from touchable opacity in 可能指的是可触摸对象,因为你正在接收this.setState 的错误不是函数,因为在 touchable 中没有诸如 setState 之类的函数。所以你必须将方法与组件绑定来更新状态,或者你可以简单地调用如下代码的函数
onPress={() => this.restartButton()}
要绑定函数,您可以在类构造函数中使用以下代码
this.restartButton= this.restartButton.bind(this);
推荐阅读
- google-apps-script - 具有 onEdit() 触发器的 Google App Scripts 中除所有者之外的其他编辑器的数据保护问题
- javascript - 查找 .then 链中哪个承诺失败
- python - 只用一行python代码实现累加和
- java - 使用线程计算子字符串的所有出现次数
- javascript - 有什么方法可以设置 CSS 动画在例如按钮开/关上以不同的方式工作?
- android - 尝试在 null 上调用虚拟方法“java.lang.String com.google.firebase.auth.FirebaseAuth.getUid()”
- twilio - 基于 Twilio 云的函数和库
- php - 如何将 Slick Slider 脚本正确添加到 Wordpress?
- javascript - 如何在等待时遍历 Firestore 快照文档
- javascript - 键值对的胡子模板