React Native onPress being called automatically

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


onPress={this.handleevent.bind(this, 'A')}

or use this:

onPress={() => this.handleevent('B')}

Change

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

to

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

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


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