React Native onPress being called automatically

前端 未结 5 1305
悲&欢浪女
悲&欢浪女 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 20:53

    The reason for such behaviour is on every render, reference to the function is created.

    So, to avoid that, use bind function OR arrow function to call on onPress

    0 讨论(0)
  • 2020-12-12 20:58

    Change

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

    to

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

    Otherwise, the function gets invoked as soon as the render method gets called.

    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-12-12 21:05
    onPress={this.handleevent.bind(this, 'A')}
    

    or use this:

    onPress={() => this.handleevent('B')}
    
    0 讨论(0)
  • 2020-12-12 21:06

    try to change

    onPress={this.handleRoute('x')} // in this case handleRoute function is called as soon as render happen

    to

    onPress={() => this.handleRoute.bind('x')} //in this case handleRoute doesn't called as soon as render happen

    0 讨论(0)
提交回复
热议问题