LoginSignup
1
0

More than 3 years have passed since last update.

Reactのイベントハンドラにおいて「Cannot read property '〇〇' of undefined」と出る

Posted at

ES6記法でReactのコードを書いていた時、イベントハンドラ内で this が使えなくなっていたので、その原因を共有します。

問題のコード

App.jsx
class App extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            status: "No"
        };
    }
    changeState() {
        this.setState({ status: "Yes" });
    }
    render() {
        return (
            <div>
                <button onClick={ this.changeState }>Change!</button>
                <div>{this.state.status}</div>
            </div>
        );
    }
}

この場合、ブラウザで実行してみると以下のように表示されます。
image.png
このボタンを押すと表示される文字が「Yes」に変わるはずなのですが、変わることはなく、下のようなエラーが発生しました。
image.png

解決策

render() 関数の onClick において、以下のように変更します。

App.jsx
<button onClick={ this.changeState.bind(this) }>Change!</button>

原因

ES5の React.createClass を使った場合はイベントハンドラが自動でbindされるのですが、ES6で React.Component を作成した場合、イベントハンドラは自動でbindされないようです。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0