Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native onPress being called automatically

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 the button on the screen. But it seems the onPress gets triggered itself when the render function is called. When i try to press manually, it doesn't work.

  import React, { Component } from 'react';   import { PropTypes, Text, View ,Alert } from 'react-native';   import { Button } from 'react-native-material-design';  export default class Home extends Component {      render() {     return (           <View style={{flex:1}}>             <Button value="Contacts" raised={true} onPress={this.handleRoute('x')} />             <Button value="Contacts" raised={true} onPress={this.handleRoute('y')} />             <Button value="Contacts" raised={true} onPress={this.handleRoute('z')} />           </View>           ); } handleRoute(route){   alert(route) // >> x , y, z      } }    module.exports = Home; 

What am i missing ? Is there something wrong with the way i have assigned or this is some bug ? Any suggestion is highly appreciated.

Video

like image 794
Sijan Shrestha Avatar asked Feb 19 '17 15:02

Sijan Shrestha


1 Answers

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

like image 102
Manjeet Singh Avatar answered Oct 04 '22 12:10

Manjeet Singh