美文网首页
React组件中的this是什么

React组件中的this是什么

作者: 季节小梅子 | 来源:发表于2019-10-22 18:36 被阅读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指向什么?

相关文章

  • 面试题

    React组件的渲染流程是什么? 使用 React.createElement或 JSX编写 React组件,实际...

  • react hook介绍

    react hook是什么 react hook是react中引入新特性,它可以让react函数组件也拥有状态;通...

  • React中ref的使用

    React中Ref是什么? ref是React提供的用来操纵React组件实例或者DOM元素的接口。 ref的作用...

  • React Native 架构之 Redux介绍

    React 在 React 中,UI 以组件的形式来搭建,组件之间可以嵌套组合。另,React 中组件间通信的数据...

  • React 进阶二 组件详解

    React组件 React的组件大概分为俩部分,无状态组件和有状态组件 无状态组件。下面React官网中定义的一个...

  • React组件中的this是什么

    React组件中的this到底是指什么?看完这篇,再也不会有疑问。-初步感受不同代码位置,this打印什么。-改变...

  • RN:React-Redux

    目录一. React-Redux是什么 1. React-Redux的组件拆分规范  1.1 UI组件  1.2 ...

  • React基础

    React包含react元素和react组件 react元素 react组件 react组件分为函数组件和类组件 ...

  • 高阶组件

    React 高阶组件HOC (Higher-Order Component) 高阶组件是react中重复使用组件逻...

  • react的受控组件和非受控组件

    受控组件就是可以被 react 状态控制的组件在 react 中,Input textarea 等组件默认是非受控...

网友评论

      本文标题:React组件中的this是什么

      本文链接:https://www.haomeiwen.com/subject/myoxuctx.html