简体   繁体   English

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

[英]Restart Countdown timer in react native

working on a countdown timer, I want to be able to restart the countdown onpress of the button, however, I don't think the button is functional as I get no feedback. 在使用倒数计时器时,我希望能够在按下按钮时重新开始倒数计时,但是,由于没有得到任何反馈,我认为该按钮不起作用。 can someone please point me in the right direction. 有人能指出我正确的方向吗? below is a trimmed down sample code of what I am trying to achieve. 下面是我要实现的精简示例代码。

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>
      )
  }
}

I believe you're looking for onPress, not Onpress. 我相信您正在寻找的是onPress,而不是Onpress。 Also, if you are using: 另外,如果您使用的是:

startTimer = () => ...

Using: 使用方法:

this.startTimer.bind

Has no effect, since the method is already bound to this by the arrow function. 无效,因为该方法已通过箭头函数绑定到此方法。 You can then simply use: 然后,您可以简单地使用:

onPress={this.startTimer}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM