TouchableXXX 将在应用程序以 reactnative 启动时自动触发

TouchableXXX will auto triggered when app start in reactnative

我正在尝试包裹 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)来控诉这个问题

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>
    );
  }
}