![](/img/trans.png)
[英]How to set button unvisible when timer count === 0 in React.js?
[英]React.js class programming not able to stop count down timer
我試圖在狀態計數達到 0 或狀態 isStopped 為真時停止計時器,然后它應該在該特定數字處停止它。 我不熟悉 React 的類編程,並且很難實現這一點。
我試圖查找它,但我不熟悉如何使用組件確實安裝來實現它。 我相信我的邏輯在組件確實安裝部分上應該是正確的但是當它在反應應用程序上為 0 時它永遠不會停止
這是我的代碼
import React, { Component } from "react";
import "./index.css";
export default class Timer extends Component {
constructor(props) {
super(props);
this.state = {
count: 10,
isStopped: false,
};
}
handleClick = () => {
this.setState({ isStopped: !this.state.isStopped });
console.log(this.state.isStopped);
};
render() {
return (
<div className="mt-100 layout-column align-items-center justify-content-center">
<div className="timer-value" data-testid="timer-value">
{this.state.count}
</div>
<button
className="large"
data-testid="stop-button"
onClick={this.handleClick}
>
Stop Timer
</button>
</div>
);
}
componentDidMount() {
if (this.state.count > 0 && this.state.isStopped == false) {
this.myInterval = setInterval(() => {
this.setState({ count: this.state.count - 1 });
}, 1000);
}
}
}
任何幫助將不勝感激謝謝:)
在componentDidMount()
,清除間隔 a/c 以聲明:
componentDidMount() {
if (this.state.count > 0 && this.state.isStopped == false) {
this.myInterval = setInterval(() => {
if (this.state.isStopped) {
clearInterval(this.myInterval);
return;
}
this.setState({ count: this.state.count - 1 });
}, 1000);
}
}
您可以使用以下登錄
componentDidMount() {
if (this.state.count > 0) {
this.myInterval = setInterval(() => {
if (this.state.isStopped) {
clearInterval(this.myInterval);
return;
}
this.setState({ count: this.state.count - 1 });
}, 1000);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.