react native onPress响应方法是否加bind(this)

前端之家收集整理的这篇文章主要介绍了react native onPress响应方法是否加bind(this)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

最近在学习react native 但是一直不明,为啥定义一个方法,在onPress中为啥要写成this.back.bind(this),我back就是一个方法为啥还要再bind(this). 其实就是一个作用域,绑定这个作用域中的方法
那么其实我们有两种写法去定义onPress的响应方法

1.不加bind(this)

onPress={this.back}
....
  back = () => {
        const {navigator} = this.props;
        navigator.pop();
    }

这种写法不用去bind了,

()=>{} 这种形式的代码,语法规定就是(function(){}).bind(this),即自动添加了bind this

2.需要加bind

onPress={this.back.bind(this)}

....

  back() {
        const {navigator} = this.props;
        navigator.pop();
    }

这种要bind的

原文链接:https://www.f2er.com/react/302391.html

猜你在找的React相关文章