在创建React类时,代码已附,触发click事件,报错,“Cannot read property 'setState' of undefined”,通过在控制台打印this,发现changeUserInfo()里的this为undefined,此时比较疑惑,解决的办法当然是给这个onClick事件改写为onClick={this.changeUserInfo.bind(this)},但是为什么changeUserInfo()里的this为undefined呢?翻到一篇文章,解释原因是:实例化组件时,changeUserInfo()中的this的上下文是div支撑的实例,而其他的this的上下文是BodyIndex实例,所以导致报错~还是没有通天,求路过的大神指教~
import React from 'react';
// var React = require('react');
export default class BodyIndex extends React.Component {
constructor () {
super();// 调用基类的所有初始化方法
this.state = {username: 'Parry', age: 20}
}
changeUserInfo() {
console.log('changeUserInfo()');
console.log(this);// undefined why???
this.setState({age: 50})
}
render () {
console.log('render()');
console.log(this); // BodyIndex Object
return (
<div>
<h2>Page Content...</h2>
<p>{this.props.userId}{this.props.userName}</p>
<p>age: {this.state.age}</p>
<input type="button" value="提交" onClick={this.changeUserInfo}/>
{/*所以要写成onClick={this.changeUserInfo.bind(this)}*/}
</div>
)
}
}