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就是组件本身 -
button2this.handleClick1 指向当前组件的
handleClick1这个箭头函数, 箭头函数内部访问的都是来自外部的this值, 此时的this由箭头函数handleClick1直接获取的组件本身 -
button3this.handleClick2 指向当前组件的
handleClick2这个函数, 而此时 this.handleClick2 中这个.点返回的不是一个函数,而是一种特殊的引用类型的值(this,"handleClick2",true), 此时再去调用handleClick2会将引用类型作为一个整体丢弃, 只获取 this.handleClick2(一个函数)的值进行传递, 失去了 this -
button4箭头函数首先访问了
render函数传递来的this,handleClick2通过.接收了这个 引用类型 ,然后当在引用类型上用()调用时,handleClick2接收到这个对象和它的方法的所有信息,并且设定正确的 this 值, 然后再执行 -
button5使用
bind()方法创建一个新的函数, 将handleClick2的this设置为给定的this(这里就是render函数传来的this)
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网
猜你喜欢:本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
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)》 这本书的介绍吧!