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 就是组件本身

  • button2

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

  • button3

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

  • button4

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

  • button5

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

转载于:https://juejin.im/post/5d060569f265da1b827a9a93

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值