[英]how to stop a timer in setInterval by click then resume by click again?
I am new to react, I am trying to write a react component, component has several features.我是 React 新手,我正在尝试编写一个 React 组件,该组件有几个特性。
I have implemented the first and second feature.我已经实现了第一个和第二个功能。 but when I try to click stop to stop number from reducing 1, it does not work.
但是当我尝试单击停止以阻止数字减少 1 时,它不起作用。
I am wondering since I used type=true/false
to indicate the state of type is start or stop.我想知道因为我使用
type=true/false
来指示类型的状态是开始还是停止。 Because in the start state, number should automatically reduce 1. And on the stop state, reducing 1 should stop.因为在开始状态,数字应该自动减1。而在停止状态,减1应该停止。 So, the timer function should accurate according to the state of type.
因此,定时器功能应根据类型的状态准确。
Also I am not sure if I used clearInterval
method right.另外我不确定我是否正确使用了
clearInterval
方法。
I really appreciate if someone could give me a hand.如果有人能帮我一把,我真的很感激。
code is here:代码在这里:
class App extends Component {
constructor(props) {
super(props);
this.state = {
details: [{ id: 1, number: "" }],
type: false
};
this.handleClick = this.handleClick.bind(this);
}
changeNumber = (e, target) => {
this.setState({
details: this.state.details.map(detail => {
if (detail.id === target.id) {
detail.number = e.target.value;
}
return detail;
})
});
};
handleClick = () => {
this.setState(prevState => ({
type: !prevState.type
}));
if (this.state.type === false) {
var myTimer = setInterval(
() =>
this.setState({
details: this.state.details.map(detail => {
if (detail.id) {
detail.number = parseInt(detail.number) - 1;
}
return detail;
})
}),
1000
);
} else if (this.state.type === true) {
clearInterval(myTimer);
}
};
render() {
return (
<div>
{this.state.details.map(detail => {
return (
<div key={detail.id}>
Number:{detail.number}
<input
type="number"
onChange={e => this.changeNumber(e, detail)}
value={detail.number}
/>
<input
type="button"
onClick={() => this.handleClick()}
value={this.state.type ? "stop" : "start"}
/>
</div>
);
})}
</div>
);
}
}
export default App;
You need to declare var myTimer
outside of the handleClick()
function.您需要在
handleClick()
函数之外声明var myTimer
。
So it's something like:所以它是这样的:
var myTimer;
...
handleClick = () => {
this.setState(prevState => ({
type: !prevState.type
}));
if (this.state.type === false) {
myTimer = setInterval(
() =>
this.setState({
details: this.state.details.map(detail => {
if (detail.id) {
detail.number = parseInt(detail.number) - 1;
}
return detail;
})
}),
1000
);
} else if (this.state.type === true) {
clearInterval(myTimer);
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.