【发布时间】:2018-05-17 11:40:37
【问题描述】:
我正在尝试实现一个简单的反应组件,它会在点击时更改名称。我在加载具有以下反应组件的页面时收到错误Error - TypeError: this is undefined。错误似乎在setState 行中。
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>
);
}
}
【问题讨论】:
-
在哪一行?很可能它在
handleClick中......常见的解决方案是在构造函数中添加this.handleClick = this.handleClick.bind(this)行 - 因为this对事件处理程序很棘手 -
这篇文章解释了 5 种不同的方法来解决这个问题的优缺点:medium.freecodecamp.org/…
标签: javascript html reactjs