bra*_*rar -1 javascript reactjs
你是如何做到的,这样每当你点击开始按钮时,计时器才会开始。因为现在,它是随意开始的。
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);
Run Code Online (Sandbox Code Playgroud)
我应该在 onClick 属性中放入什么?
小智 5
您需要将“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);
Run Code Online (Sandbox Code Playgroud)
希望有帮助。
| 归档时间: |
|
| 查看次数: |
3818 次 |
| 最近记录: |