【问题标题】:TouchableXXX will auto triggered when app start in reactnative当应用程序以响应式启动时,TouchableXXX 将自动触发
【发布时间】:2018-01-31 19:08:18
【问题描述】:

我正在尝试包装this tortial 之后的可触摸项目

我发现的问题是导航将在应用程序启动时自动触发,它会导航到详细信息页面而无需按下它。 并且当往回导航时,可触摸的项目不能再被按下,按下时会抛出错误。

我制作了一个最低限度的应用程序来控诉这一点:

import React , { Component } from 'react';
import { StyleSheet,FlatList, Text, View,TouchableOpacity } from 'react-native';
import {
  StackNavigator,
} from 'react-navigation';


class Detail extends Component {
  static navigationOptions = {
    title: "Detail",
  };

  render(){
    return(
      <View>
          <Text>{this.props.value}</Text>
      </View>
    );
  }
}

class MyItem extends Component{
  render(){
    return(
      <View>
        <TouchableOpacity onPress={this.props.nav("Detail", {value: this.props.value})}>
        <Text> {this.props.value}</Text>
        </TouchableOpacity>
      </View>
    );
  }
}

class Home extends React.Component {
  static navigationOptions = {
    title: "Home",
  };
  render() {
    const {navigate} = this.props.navigation;
    return (
      <View style={styles.container}>
        <FlatList
          data = {[
            {key: "1"},
            {key: "2"},
            {key: "3"}
          ]
          }
          renderItem = {({item}) => <MyItem nav={navigate} value={item.key} />}
        />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

const App = StackNavigator({
  Home: { screen: Home },
  Detail: { screen: Detail },
})

export default App

由于我的英语不好很难描述这个问题,所以我也发了youtube video (about 20M)来控诉这个问题

【问题讨论】:

    标签: react-native touchablehighlight onpress


    【解决方案1】:
    class MyItem extends Component{
      render(){
        return(
          <View>
            <TouchableOpacity onPress={() => { this.props.nav("Detail", {value: this.props.value})} }>
            <Text> {this.props.value}</Text>
            </TouchableOpacity>
          </View>
        );
      }
    }
    

    根据要求

    class MyItem extends Component{
      handleClick = () => {
        const { nav, value } = this.props;
        nav("Detail", {value});
      }
      render(){
        return(
          <View>
            <TouchableOpacity onPress={this.handleClick}>
            <Text> {this.props.value}</Text>
            </TouchableOpacity>
          </View>
        );
      }
    }
    

    【讨论】:

    • 如果我想像教程在这种情况下那样创建_onPressButton(value) 函数,你能举个例子吗?谢谢。不知道如何将所有这些参数传递给函数。
    • 我已经更新了我的答案,如果出现任何问题,请告诉我。
    猜你喜欢
    • 1970-01-01
    • 2017-07-30
    • 2011-03-27
    • 1970-01-01
    • 2010-11-11
    • 2011-04-06
    • 2011-12-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多