码迷,mamicode.com
首页 > 其他好文 > 详细

react中的this

时间:2018-04-11 18:08:42      阅读:175      评论:0      收藏:0      [点我收藏+]

标签:总结   pre   define   一个   返回   最大的   cli   undefined   value   

今天被问到了一个关于react中this指向的问题,脑子里大概有一些概念,但是一时又说不太清楚,之后查了一些资料,按照自己的理解总结一下

 

es6的class是可以用来构建react组件的一种方式,而我们在构建组件的时候其实就是创建类,这时候我们并没办法知道this的上下文,而其后组件被调用,其实就是实例化了一个对象,这时候,组件有上下文了,我们可以开始讨论this了

 

 1 import React from ‘react‘
 2 
 3 export default class MyComponent extends React.Component{
 4     constructor(props) {
 5         super(props)
 6         this.state = {
 7             name: ‘W‘
 8         }
 9         this.value = ‘www‘
10         this.handler1 = this.handler1.bind(this)
11     }
12     handler() {
13         console.log(this)
14     }
15     handler1() {
16         console.log(this)
17     }
18     handler2 = () => {
19         console.log(this)
20     }
21     componentDidMount() {
       console.log(‘***componentDidMount***: ‘,this) 
22 console.log(‘***componentDidMount this handler***: ‘,this.handler()) 23 console.log(‘***componentDidMount this handler1***: ‘,this.handler1()) 24 console.log(‘***componentDidMount this handler2***: ‘,this.handler2()) 25 } 26 render() { 27 console.log(‘***render this***: ‘,this) 28 console.log(‘***render this handler***: ‘,this.handler()) 29 console.log(‘***render this handler1***: ‘,this.handler1()) 30 console.log(‘***render this handler2***: ‘,this.handler2()) 31 return ( 32 <div> 33 <button onClick={this.handler}>click me</button> 34 <button onClick={this.handler1}>click me</button> 35 <button onClick={this.handler2}>click me</button> 36 </div> 37 ) 38 } 39 }

首先,componentDidMount() 和 render()中的this输出的是该实例对象,以此类推,我们可以测试其他生命周期,最终会发现在构造函数等一系列生命周期中,我们调用的this都是指向实例对象的

其后,我们看到这里我定义了三个函数,而对三个函数调用的时候我们也是通过this来调用的,因为上面我们已经说过,这些情况下的this指向实例对象,而函数也是定义在实例对象里的
而关键的地方便是在函数内部的this,我们会发现handler函数无论是在生命周期中调用,还是在button中触发调用,this都是返回undefined。这是因为es6的class并没有帮助我们绑定函数的上下文,
所以在实例化的时候,handler()的上下文其实是button了,而我们想要的效果是让其绑定在MyComponent实例上
为了解决这个问题,我们必须手动来绑定,于是有了handler2,我们通过bind来将其上下文绑定到‘this’上,而这个‘this’我们之前验证过了,就是实例对象
当然,除了通过bind绑定,es6给我们提供了一个新的概念:箭头函数,它最大的特征便是把函数的this绑定到其定义时所在的上下文,而从代码中我们也可知,箭头函数便是被定义在类中,实例化的时候,其上下文自然是实例对象

通过一个this,这个问题里面还有讨论到class构建组件,组件实例化,箭头函数,bind绑定,都是需要了解并且值得深入的

react中的this

标签:总结   pre   define   一个   返回   最大的   cli   undefined   value   

原文地址:https://www.cnblogs.com/waiting-h/p/8797067.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!