React Native onPress 被自动调用

React Native onPress being called automatically

我在使用 react-native onPress 功能时遇到问题。 onPress 应该只在它实际被触摸事件触发时才起作用(我想),也就是当我按下屏幕上的按钮时。但似乎在调用渲染函数时 onPress 会自行触发。当我尝试手动按下时,它不起作用。

  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;

我错过了什么?我分配的方式有问题还是这是一些错误? 非常感谢任何建议。

Video

尝试改变

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

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

你可以改成这样:

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

或者这个:

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

原因是onPress接受一个函数作为参数。在您的代码中,您正在调用该函数并立即返回结果(当调用渲染时),而不是 引用 React 稍后在按下事件时调用的函数。

你需要 bind(this) 的原因是因为函数在你刚刚执行 (this.handleRoute) 时失去了它的绑定实例,你必须告诉它哪个 this 使用。绑定函数采用其他参数稍后调用该函数。有关绑定的更多描述性信息,请参阅 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

还有另一种方法可以在构造函数中进行绑定。您可以在此处阅读有关在 React 中处理此问题的方法:https://facebook.github.io/react/docs/handling-events.html

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

或者使用这个:

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

改变

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

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

否则,一旦调用 render 方法就会调用该函数。

这种行为的原因是在每次渲染时,都会创建对函数的引用。

因此,为避免这种情况,请使用绑定函数或箭头函数来调用 onPress