Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
603 views
in Technique[技术] by (71.8m points)

javascript - How to restart timer at the onPress in react native

I have made a small functionality for timer, where a timer will countdown from 10. When it reaches 0, the timer will hide, and a restart button will come at that place. Till this far, I am able to do it.

But I wanted to restart the timer when Restart appears after countdown is completed.

Below is the code:

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>

As you can see, Restart appears when countdown is finished, But when I click on Restart it is showing me error: Cannot read property 'setState' of undefined.

question from:https://stackoverflow.com/questions/65843860/how-to-restart-timer-at-the-onpress-in-react-native

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In the class component, we cannot directly call the methods that use this keyword as an in-class component this keyword refers to the object it called from as here it called from touchable opacity in might refers as the touchable object because of that you are receiving the error for this.setState is not a function as there is no function such as setState in touchable. so you have to bind the methods with a component to update the state or you can simply call the function as below code

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

To bind the function you can use the below code in your class constructor

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...