javascript - 在 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);
希望有帮助。
推荐阅读
- r - 根据闪亮应用程序中的参数1值隐藏/显示参数2
- java - 测试容器超时等待容器端口打开,使用 Elasticsearch docker 镜像
- reactjs - React Hook Form - 在不清除表单的情况下重置“isDirty”?
- xamarin.forms - 在 Debug 中工作但在 Microsoft Store 中不工作的图像 - UWP Xamarin.Forms
- vue.js - 如何使用 VueJS 在 DOM 中附加子组件?
- python - 使用 Python 使用 modbus 协议命令远程 PLC
- visualization - graphviz dot HTML 属性不起作用?
- javascript - 从结果中自动创建变量名?
- python - 我们可以在自己的方法中传递类对象吗?
- java - 模拟类的非静态方法