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

react-调用函数this丢失问题

时间:2020-08-24 16:37:47      阅读:49      评论:0      收藏:0      [点我收藏+]

标签:class   mic   component   def   实例   efault   exp   line   button   

调用事件处理函数,this指向函数,this不是指向实例,解决这个问题就是给调用函数时bind(this)改变this指向或者使用箭头函数

1、bind改变this指向

export default class Home extends Component {
    constructor(){
        super()
        //改变test函数的this指向到实例
        this.test = this.test.bind(this);
    }
    test(){
        console.log(this)
    }
}

技术图片

2、ES6方法

//函数正常写
test(){
    console.log(this)
}
//调用时使用箭头函数保留this指向
<Button onClick={()=>this.test()} type="primary" inline>点击</Button>

3、ES7方法

test=()=>{
    console.log(this)
}

react-调用函数this丢失问题

标签:class   mic   component   def   实例   efault   exp   line   button   

原文地址:https://www.cnblogs.com/piaoyi1997/p/13529528.html

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