Search code examples
react-nativetouchablehighlightonpress

TouchableXXX will auto triggered when app start in reactnative


I am trying to wrap touchable items following this tortial

And the problem I found is that the navigation will be auto trigger by the launch of the app, it will navigate to the detail page without press on it. And when navigate back, the touchable items can't be pressed anymore, when pressed, an error will be thrown out.

I made a minimum app to indict that out:

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

Since it's very hard to describe this issue with my bad English, I also made a youtube video (about 20M) to indict this problem


Solution

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

    As per request

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