React Native onPress being called automatically

前端 未结 5 1368
悲&欢浪女
悲&欢浪女 2020-12-12 20:20

I am having trouble with react-native onPress Feature. The onPress should only work when it is actually been triggered by a touch event (i suppose) , that is when i press th

5条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-12 21:01

    You can change to this:

    onPress={this.handleRoute.bind(this, 'x')}
    

    or this:

    onPress={() => this.handleRoute('x')}
    

    The reason is that onPress takes a function as an argument. In your code, you are calling the function and returning the result immediately (when render is called) rather than referencing the function for React to call later on the press event.

    The reason you need the bind(this) is because the function loses it's bound instance when you just do (this.handleRoute) and you have to tell it which this to use. The bind function takes the other arguments to call on the function later. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind for more descriptive info on bind.

    There is another way in which you can bind in the constructor. You can read about ways to handle this in React here: https://facebook.github.io/react/docs/handling-events.html

提交回复
热议问题