React组件中的this是什么

2019-10-22  本文已影响0人  季节小梅子

React组件中的this到底是指什么?看完这篇,再也不会有疑问。
-初步感受不同代码位置,this打印什么。
-改变自定义方法的"调用者",看看this打印什么。
-该如何手动绑定this。

编写下面这个组件,将其渲染出来。

import React from 'react';
const suffix = '被调用,this指向:';
export default class ReactThis extends React.Component {
  handler() {
    console.log(`handler${suffix}`, this)
  }
  render() {
    console.log(`render${suffix}`, this)
    return (
      <div>
        <h2 onClick={this.handler}>Hello React</h2>
      </div>
    );
  }

}

结果是,render()函数中的this指向了组件实例,而handler()函数中的this则是一个undefined。


image.png
image.png

自定义方法的"调用者"不同导致this不同。("调用者"是指函数执行时的当前对象)

分别在组件自带的生命周期函数以及自定义的handler()方法中打印this,并在render()方法里分别使用this.handler()、window.handler()、onClick={this.handler}这三种方法调用handler(),看看this的指向。

import React from 'react';
const suffix = '被调用,this指向:';
export default class ReactThis extends React.Component {
  componentWillMount(){
    console.log(`componentWillMount${suffix}`, this)
  }
  componentDidMount(){
    console.log(`componentDidMount${suffix}`, this)
  }
  componentWillReceiveProps(){
    console.log(`componentWillReceiveProps${suffix}`, this)
  }
  shouldComponentUpdate(){
    console.log(`shouldComponentUpdate${suffix}`, this)
  }
  componentWillUpdate(){
    console.log(`componentWillUpdate${suffix}`, this)
  }
  componentDidUpdate(){
    console.log(`componentDidUpdate${suffix}`, this)
  }
  componentWillUnmount(){
    console.log(`componentWillUnmount${suffix}`, this)
  }
  
  handler() {
    console.log(`handler${suffix}`, this)
  }
  render() {
    console.log(`render${suffix}`, this)
    this.handler()
    window.handler = this.handler;
    window.handler();
    return (
      <div>
        <h2 onClick={this.handler}>Hello React</h2>
      </div>
    );
  }

}

运行程序后发现,
render()以及componentWillMount()、componentDidMount()等其他生命周期函数中的this,都是指向组件实例。
window.handler()中的this指向了window。
onClick={this.handler}中的this打印了undefined。


image.png

没有自动绑定

如果this没有指向组件实例,是无法使用state等组件实例对象的属性的。
但是React组件中没有实现this的自动绑定,函数的"调用者不同"导致this的指向不同。具体this是指什么,React把这种上下文转换的自由权交给了开发者。

手动绑定this

1、在构造函数里绑定

constructor(){
    super()
    this.state = {}
    this.handler = this.handler.bind(this)
  }

绑定之后,触发点击事件,this已经指向组件实例了。


image.png

在构造函数里绑定this的好处是,仅需绑定一次,避免每次渲染时都要重新绑定,函数在别处复用时也不需要再次绑定了。
2、在属性中临时绑定

render() {
    console.log(`render${suffix}`, this)
    this.handler()
    window.handler = this.handler;
    window.handler();
    return (
      <div>
        <h2 onClick={this.handler.bind(this)}>Hello React</h2>
        <div>value:{this.state.value}</div>
      </div>
    );
  }

3、使用箭头函数

render() {
    console.log(`render${suffix}`, this)
    this.handler()
    window.handler = this.handler;
    window.handler();
    return (
      <div>
        <h2 onClick={()=>{this.handler()}}>Hello React</h2>
        <div>value:{this.state.value}</div>
      </div>
    );
  }

箭头函数会捕获其所在上下文的this值,作为自己的this值。
4、es7写法

handler=()=> {
    console.log(`handler${suffix}`, this)
  }
  render() {
    console.log(`render${suffix}`, this)
    this.handler()
    window.handler = this.handler;
    window.handler();
    return (
      <div>
        <h2 onClick={this.handler}>Hello React</h2>
        <div>value:{this.state.value}</div>
      </div>
    );
  }

然而es6并不支持es7写法,不过没关系,安装一个babel-preset-stage-0
配置一下.babelrc,就可以支持了。

"presets": [
    "es2015",
    "stage-0",
    "react"
  ],

这么多手动绑定this的方法,推荐 1,3,4。

外传:

var person = {
  speak: function() {
    console.log(this)
  }
}
person.speak();
var _speak = person.speak;
_speak()

person.speak() this指向什么?
_speak()this指向什么?

又一个外传:

var person = {
  speak: ()=> {
    console.log(this)
  }
}
person.speak();
var _speak = person.speak;
_speak()

person.speak() this指向什么?
_speak()this指向什么?

上一篇 下一篇

猜你喜欢

热点阅读