从类中this看react中事件绑定

232 阅读1分钟

首先看下面这段代码

class Person {
    constructor(name,age){
            this.name = name
            this.age = age
    }
    study(){
            console.log(this);
    }
}

const p1 = new Person('tom',18)
p1.study() //通过实例调用study方法
const x = p1.study
x()

study方法放在了哪里?——类的原型对象上,供实例使用,如图

image.png

通过Person实例调用study时,study中的this就是Person实例,下面的x中的this为什么是undefined呢? 输出x看看,如图,x是一个函数

image.png

函数中this默认指向全局对象,即window,但为什么输出是undefined呢? 因为类中的方法默认开启了严格模式,严格模式下,函数的this即为undefined。

再回到react中,看下面这段代码

class Weather extends React.Component{
    constructor(props){
            console.log('constructor');
            super(props)
            this.state = {isHot:false,wind:'微风'}
            //解决changeWeather中this指向问题
            this.changeWeather = this.changeWeather.bind(this)
    }

    render(){
            console.log('render');
            const {isHot,wind} = this.state
            return <h1 onClick={this.changeWeather}>今天天气很{isHot ? '炎热' : '凉爽'},{wind}</h1>
    }

    changeWeather(){
            console.log('changeWeather');
            const isHot = this.state.isHot
            this.setState({isHot:!isHot})
            console.log(this);
    }
}
ReactDOM.render(<Weather/>,document.getElementById('test'))

由于changeWeather是作为onClick的回调,所以不是通过实例调用的,是直接调用,相当于类上面代码中的x,所以可以直接在类实例中添加changeWeather方法,即

this.changeWeather = this.changeWeather.bind(this)

image.png

这样就可以解决this指向问题

写在末尾:第一次写笔记,可能写的不怎么好,排版之类的,以后会慢慢改进的