私はクリック時に名前を変更する簡単な反応コンポーネントを実装しようとしています。私は下のコンポーネントを反応している私のページを読み込んでいる間、エラーの下になっています。 何が間違っていますか?私はJavascriptとReact JSのかなり新しいです。エラーがsetstate行にあるようです。TypeError:これは未定義です - React JS、Javascript
エラー - 例外TypeError:これはあなたがhandleClickメソッドのコンストラクタでこれをバインドする必要が未定義
class Layer5 extends React.Component {
constructor(props) {
super(props);
this.state = {buttonstate: false};
}
componentDidMount() {
}
componentWillUnmount() {
}
handleClick(e) {
e.preventDefault();
this.setState({buttonstate: !this.state.buttonstate});
}
render() {
var icon = this.state.buttonstate ? 'images/image1.png' : 'images/image2.jpg';
return (
<div className="layer5">
<a href="#" onClick={this.handleClick}><img src={icon} ></img></a>
</div>
);
}
}
いずれこれがエラーである - はTypeError:これはライン上の不定 – codinglover
ですか? 'handleClick'にある可能性があります...一般的な解決方法は、' this.handleClick = this.handleClick.bind(this) 'をコンストラクタ内に置くことです。これはイベントハンドラでは「this」が扱いにくいからです。 –
この記事では、長所と短所でこの問題を解決するアプローチ:https://medium.freecodecamp.org/react-binding-patterns-5-approaches-for-handling-this-92c651b5af56 –