类的方法默认不会绑定this,因此在调用的时候如果忘记绑定,this的值将会是undefined。所以需要手动绑定事件。React中给元素绑定事件,主要有以下几种方式
构造器使用bind绑定this
import React, {Component} from 'react';class Button extends React.Component {//构造器 render函数 组件生命周期可以获取到组件实例对象也就是thisconstructor(props) {super(props);this.handleClick = this.handleClick.bind(this);/*左侧this.handleClick是给组件实例对象上挂载一个属性右侧this.handleClick.bind(this)先通过__proto__获取原型对象的handleClick方法,再将其binding到this上二者结合,就将右侧找到的方法挂载到组件实例对象上了*/}handleClick(){ //给Button类添加自定义事件,handleClick函数只能在类的原型对象上console.log('this is:', this);}render() {return (<button onClick={this.handleClick}>Click me</button>//当然 这个binding还可以写在JSX中 在调用的时候同时binding<button onClick={this.handleClick.bind(this)}>Click me</button>);}}
绑定箭头函数,执行时通过this调用事件
import React, {Component} from 'react';class Button extends React.Component {handleClick(){console.log('this is:', this);}render() {return (//点击事件绑定的是箭头函数,箭头函数在执行的时候已经可以访问this 直接通过this调用<button onClick={()=>this.handleClick()}>Click me</button>);}}
属性初始化语句绑定this
import React, {Component} from 'react';class Button extends React.Component {//给Button组件初始化一个属性handleClick,值为箭头函数//箭头函数没有自己的this,在执行时候找外部也就是render函数的this,也就是组件实例对象handleClick=()=>{console.log('this is:', this);}render() {return (<button onClick={this.handleClick}>Click me</button>);}}
