react组件中的this的一点理解

栏目: IOS · Android · 发布时间: 7年前

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 )


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Pro Git

Pro Git

Scott Chacon / Apress / 2009-8-27 / USD 34.99

Git is the version control system developed by Linus Torvalds for Linux kernel development. It took the open source world by storm since its inception in 2005, and is used by small development shops a......一起来看看 《Pro Git》 这本书的介绍吧!

在线进制转换器
在线进制转换器

各进制数互转换器

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具