react组件中的this的一点理解

刚学不久,本身的一点理解,不对的地方你们使劲喷,但你要告诉我对的

import React, { Component } from 'react'

class Demo extends Component{
    handleClick1 = () =>{
        console.log(this)
    }
    handleClick2(){
        console.log(this)
    }
    render(){
        return (
            <div> <button onClick={console.log(this)}>button1</button> <button onClick={this.handleClick1}>button2</button> <button onClick={this.handleClick2}>button3</button> <button onClick={()=>this.handleClick2()}>button4</button> <button onClick={this.handleClick2.bind(this)}>button5</button> </div>
        )
    }
}
export default Demo
复制代码
  • button1

    不用多说直接执行, this 就是组件自己react

  • button2

    this.handleClick1 指向当前组件的 handleClick1 这个箭头函数, 箭头函数内部访问的都是来自外部的 this 值, 此时的 this 由箭头函数 handleClick1 直接获取的组件自己函数

  • button3

    this.handleClick2 指向当前组件的 handleClick2 这个函数, 而此时 this.handleClick2 中这个 . 点返回的不是一个函数,而是一种特殊的引用类型的值(this,"handleClick2",true), 此时再去调用 handleClick2 会将引用类型做为一个总体丢弃, 只获取 this.handleClick2(一个函数)的值进行传递, 失去了 thisui

  • button4

    箭头函数首先访问了 render 函数传递来的 thishandleClick2 经过 . 接收了这个 引用类型 ,而后当在引用类型上用 () 调用时,handleClick2 接收到这个对象和它的方法的全部信息,而且设定正确的 this 值, 而后再执行this

  • button5

    使用 bind() 方法建立一个新的函数, 将 handleClick2this 设置为给定的 this (这里就是 render 函数传来的 this)spa

相关文章
相关标签/搜索