首页 > 解决方案 > 如何在反应原生的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

标签: javascriptreact-nativetimer

解决方案


在类组件中,我们不能直接调用使用 this 关键字作为类内组件的方法 this 关键字指的是它调用的对象,因为这里它调用 from touchable opacity in 可能指的是可触摸对象,因为你正在接收this.setState 的错误不是函数,因为在 touchable 中没有诸如 setState 之类的函数。所以你必须将方法与组件绑定来更新状态,或者你可以简单地调用如下代码的函数

onPress={() => this.restartButton()}

要绑定函数,您可以在类构造函数中使用以下代码

this.restartButton= this.restartButton.bind(this);


推荐阅读