【问题标题】:React Native onPress being called automatically自动调用 React Native onPress
【发布时间】:2017-02-19 15:45:47
【问题描述】:

我在使用 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

【问题讨论】:

  • 我只接触过一次reactjs,但我认为你是在调用函数而不是分配它。

标签: react-native-android


【解决方案1】:

尝试改变

onPress={this.handleRoute('x')} // 在这种情况下,一旦渲染发生,handleRoute 函数就会被调用

onPress={() => this.handleRoute.bind('x')} //在这种情况下,handleRoute 不会在渲染发生时立即调用

【讨论】:

  • 知道为什么会出现这种行为吗?
  • 不清楚(我不想提供虚假信息),会尽快通知您
  • 花了很多时间才明白。这很令人困惑,但是当您设置它时: onPress={this.click(args)} 这意味着您正在调用一个函数,并且在调用 render() 或创建按钮/可触摸对象时调用了此函数。所以,你需要使用 onPress={() => this.function(args)}。清楚了吗?
  • 但在我的情况下,存在功能组件行为,因此 this 或 bind both 不起作用。请帮助我
【解决方案2】:

你可以改成这样:

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

或者这个:

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

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

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

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

【讨论】:

  • 因为我是 React Native 的新手,所以我被困了 2 个小时......但你的回答在一分钟内解决了它。非常感谢
  • 非常感谢 React Native 新手的准确回答和解释!
【解决方案3】:

改变

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

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

否则,只要调用 render 方法就会调用该函数。

【讨论】:

    【解决方案4】:
    onPress={this.handleevent.bind(this, 'A')}
    

    或者使用这个:

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

    【讨论】:

      【解决方案5】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-11-24
        • 2017-11-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-09-19
        相关资源
        最近更新 更多