React Native onPress 被自动调用 [英] React Native onPress being called automatically

查看:47
本文介绍了React Native onPress 被自动调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

视频

推荐答案

尝试改变

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

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

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

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

这篇关于React Native onPress 被自动调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆