Azadeh:
私はリセットボタンでタイマーを作成したいです。私が反応によって書かれた初期のコードでこの演習を行う必要があります。これは、最初のコードです。
import React, {Component} from 'react';
import './Timer.css';
export class Timer extends Component {
render() {
return <div className="container">
<div className="timer">
</div>
<button>Reset Timer</button>
</div>;
}
}
私は2つの解決策を試してみたが、それらのそれぞれが異なるエラーを返しました。ここに私の最初のソリューションです。(図1) 図1
エラーが(図2) 図2
そして、私の第二の溶液はこれです...(図3) 図3
import React, {Component} from 'react';
import './Timer.css';
const initialState = {
seconds: 0
}
export class Timer extends Component {
constructor(props) {
super(props);
this.state = initialState;
}
tick() {
this.setState(state => ({
seconds: state.seconds + 1
}));
}
componentDidMount() {
this.interval = setInterval(() => this.tick(), 1000);
}
componentWillUnmount() {
clearInterval(this.interval);
}
resetTimer() {
this.setState(initialState);
}
render() {
return <div className="container">
<div className="timer">
{this.state.seconds}
</div>
<button onClick = {this.resetTimer}>Reset Timer</button>
</div>;
}
}
そしてそのエラーは、...(図4)である 。図4
どのように私は、タイマーをリセットする問題を解決することができますか?
Reda.a:
問題は、「この」スコープから来ています。
どちらのあなたは、クラスで使用している機能をバインドする必要があります。
constructor( props ){
super( props );
this.resetTimer = this.resetTimer.bind(this);
}
2番目のオプションは、あなたが「この」クラス上の範囲を維持するために、あなたの関数を宣言するときに矢印の機能を使用することです。
resetTimer = () => {
this.setState(initialState);
}