本文介绍了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.bind('x')}//在这种情况下handleRoute不会在渲染发生时立即调用

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

09-10 19:48