简体   繁体   中英

How do i pass item data from Flatlist in react native

I'm new to react. I have my App.js page that contains the main code, and a lists.js page in another folder that contains the list itself.

I import from lists.js into my App.js. It works fine.

I'm trying to set an onPress action for the listItems that also sends a unique ID to the next page that I can use to call out items in the new page.

For clarity, if i was to do this with a normal button, it will look like:

this.props.navigation.navigate('NextPage', { Email: UserEmail });

So how do i do this with a ListView that I imported from another file.

This is how my code is structured

App.js

import MarketList from './lists/markets';

class ProfileActivity extends Component
{

   static navigationOptions =
   {
      title: 'Home',
      headerStyle : {
        backgroundColor: '#00b47a'
      },
      headerTitleStyle: {
        color: 'white'
      },
      headerLeft: null,
      headerRight: (
        <Icon containerStyle={{ paddingRight: 15 }}
        color='#000' onPress={()=> navigation.getParam('openBottomSheet')()}
        name="menu" />
      )
   };

   constructor () {
    super()
    this.state = { toggled: false }
  }

  render() {
    return (
      <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center'}}>
        <MarketList />
      </View>
    );
  }
}            

My lists.js

export default class MarketList extends React.Component {
  constructor(props) {
 
    super(props)
 
    this.state = {
      items: '',
    };
  }

  render() {
    fetch('https://example.php')
    .then((response) => response.json())
    .then((json) => {
      this.setState({
        items: json.items,
      })
    })
    .catch((error) => {
      console.error(error);
    });
    return (
      <View style={styles.container}>
        <FlatList
          data={this.state.items}
          renderItem={({item}) => <TouchableOpacity onPress={} style={styles.itemList}><View style={styles.item}><Text style={styles.market}>{item.name}</Text><Text style={styles.location}>{item.Location}</Text></View><View style={styles.go}><Icon name="arrow-right" color="#00b47a" /></View></TouchableOpacity>}
        />
      </View>
    );
  }
}

You can do something like below

Pass navigation as a prop to MarketList component

  <MarketList navigation={this.props.navigation}/>

And use like below

renderItem={({item}) => <TouchableOpacity onPress={()=>this.props.navigation.navigate("pagename",{item:item})}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM