![](/img/trans.png)
[英]How to set button unvisible when timer count === 0 in React.js?
[英]Start the timer when button is clicked in React.Js
你是怎么做到的,只要你点击开始按钮,计时器就会开始。 因为现在,它是随意开始的。
class Timer extends React.Component {
constructor(props) {
super(props);
this.state = { seconds: 0 };
}
tick() {
this.setState(prevState => ({
seconds: prevState.seconds + 1
}));
}
componentDidMount() {
this.interval = setInterval(() => this.tick(), 1000);
}
componentWillUnmount() {
clearInterval(this.interval);
}
render() {
return (
<div>
Seconds: {this.state.seconds}
<br />
<button onClick={this.tick}> Start </button>
</div>
);
}
}
ReactDOM.render(<Timer />, mountNode);
我应该在 onClick 属性中放入什么?
您将需要将“ tick”绑定到构造函数中的组件,并将用于启动计时器的代码从“ componentDidMount”移动到“ tick”,如下所示:
class Timer extends React.Component {
constructor(props) {
super(props);
this.state = { seconds: 0 };
this.tick = this.tick.bind(this); // bind to the component
}
tick() {
// start timer after button is clicked
this.interval = setInterval(() => {
this.setState(prevState => ({
seconds: prevState.seconds + 1
}));
}, 1000);
}
componentWillUnmount() {
clearInterval(this.interval);
}
render() {
return (
<div>
Seconds: {this.state.seconds}
<br />
<button onClick={this.tick}> Start </button>
</div>
);
}
}
ReactDOM.render(<Timer />, mountNode);
希望能有所帮助。
这就是我们如何使用 React Hooks 实现相同的目标。
const Timer = () => {
const [isActive, setIsActive] = useState(false);
const [seconds, setSeconds] = useState(0);
useEffect(() => {
let timer = null;
if(isActive){
timer = setInterval(() => {
setSeconds((seconds) => seconds + 1);
}, 1000);
}
return () => {
clearInterval(timer);
};
});
return (
<div>
Seconds: {seconds}
<br />
<button onClick={()=>{
setIsActive(true);
}}> Start </button>
</div>
);
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.