1 class ClickCounter extends Component {
 2     constructor(props) {
 3         super(props);
 4         this.state = {count : 0};
 5     }
 6 
 7     onClickButton() {
 8         // console.log(this);
 9         this.setState({count: this.state.count + 1});
10     }
11 
12     render() {
13         return(
14             <div>
15                 <button onClick={this.onClickButton}>Click Me</button>
16                 <div>count : {this.state.count}</div>
17             </div>
18         );
19     }
20 }

点击发现state中的count并不会增加,原因为普通函数中内层函数不能从外层函数中继承this的值,在内层函数中,this会是window或者undefined

所以this.onClickButton方法的this实际上为undefined。

或者用一个抽象的例子来表达:

const test = {
    name:'jack',
    getJack:function(){
        console.log(this.name)
    }
}
const func = test.getJack;
func();

这里的func方法(getJack方法)中的this为window,并非test

对于react来说,onClick就好比func,onClickButton就好比getJeck,所以也无法得到预期中的结果。

解决方案:

1.  onClick={this.onClickButton.bind(this)}

// 有点丑

2. constructor(props){...; this.onClickButton=this.onClickButton.bind(this);...;}

3. onClickButton = () => {.......}

 

React中要注意,在一个方法中调用this.setState()等函数,或者在render()方法中被调用,都有内层函数参与,因此需要将该方法的this绑定到class。所以如果是用function的普通方法定义,需要在constructor中bind(this)【2】,如:

this.onChange = this.onChange.bind(this);

这样this指向组件实例,就可以在render()中使用,也可以在方法中调用this.setState()方法

或者直接用箭头函数进行定义【3】。

this继承自父级方法render(), 而render()的this为组件实例。这样一来,在render()中就可以愉快的使用了