React Native onPress being called automatically

久未见 提交于 2019-12-17 23:36:34

问题


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


回答1:


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




回答2:


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




回答3:


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

or:

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



来源:https://stackoverflow.com/questions/42329240/react-native-onpress-being-called-automatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!