我想为我的项目添加一个倒数组件。我尝试通过设置setInterval来尝试,但是我需要暂停并继续计时器。那么我该如何实现呢?
答案 0 :(得分:1)
我创建了一个jsfiddle,其中有一个简单的演示如何完成它:https://jsfiddle.net/69z2wepo/258601/。使用React编写,但原理与React Native完全相同。
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = {
counter: 10,
};
this.interval = null;
this.cleanUp = this.cleanUp.bind(this);
this.decreaseCounter = this.decreaseCounter.bind(this);
this.startCounter = this.startCounter.bind(this);
}
componentWillUnmount() {
cleanUp();
}
cleanUp() {
clearInterval(this.interval);
}
decreaseCounter() {
if (this.state.counter === 0) {
return this.cleanUp();
}
this.setState({counter: this.state.counter - 1});
}
startCounter() {
this.interval = setInterval(this.decreaseCounter, 1000);
}
render() {
return (
<div>
<button onClick={this.startCounter}>Start</button>
Counter {this.state.counter}
<button onClick={this.cleanUp}>Stop</button>
</div>
);
}
}