react-调用函数this丢失问题

调用事件处理函数,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)
}
原文地址:https://www.cnblogs.com/piaoyi1997/p/13529528.html