react组件中的this的一点理解

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

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 )


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

查看所有标签

猜你喜欢:

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

Designing with Web Standards (2nd Edition)

Designing with Web Standards (2nd Edition)

Jeffrey Zeldman / Peachpit Press / 2006-07-06 / USD 44.99

Best-selling author, designer, and web standards evangelist Jeffrey Zeldman has updated his classic, industry-shaking guidebook. This new edition--now in full color--covers improvements in best prac......一起来看看 《Designing with Web Standards (2nd Edition)》 这本书的介绍吧!

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

各进制数互转换器

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试