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();
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

这种写法不用去bind了,

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

2.需要加bind

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

....

  back() {
        const {navigator} = this.props;
        navigator.pop();
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

这种要bind的

猜你喜欢

转载自blog.csdn.net/nimeghbia/article/details/81838484
今日推荐