React-Native How to handle onPress from Item in flatlist ???

Viewed 19111

My FlatList is stateless component, and when item pressed I want to handle onPress by call method "handleOnPress". How can I do it ?? the below is sample codes.
`

handleOnPress = () => {
  .....
}
<SampleListView
    data={prop.data}
    onPress={this.handleOnPress}
/>
const SampleListView = (props: Props) => {
  return (
    <FlatList
        style={styles.container}
        data={props.data}
        keyExtractor={item => item.id.toString()}
        renderItem={renderItem}
    />
    )
}
renderItem = ({ item }: { item: DataSample }) => {
  return (
  <TouchableWithoutFeedback onPress={ () => props.onPress}>
      ....
  </TouchableWithoutFeedback>
  )
}

`

2 Answers

Can you try this out?

handleOnPress = () => {
  .....
}
<SampleListView
    data={prop.data}
    onPress={this.handleOnPress}
/>
const SampleListView = (props: Props) => {
  return (
    <FlatList
        style={styles.container}
        data={props.data}
        keyExtractor={item => item.id.toString()}
        renderItem={renderItem}
    />
    )
}
renderItem = ({ item }: { item: DataSample }) => {
  return (
    <TouchableWithoutFeedback onPress={props.onPress}>
      <View>
        ....
      </View>
    </TouchableWithoutFeedback>
  )
}

Please pay attention to that 2 links.

https://facebook.github.io/react-native/docs/flatlist

TouchableWithoutFeedback with custom component inside doesn't fires onPress callback

The differences are, giving callback as param and adding View layer.

Problem with your code is this onPress={props.onPress} your renderItem function does not know (props) all it knows are the item parameter passed to it.

If you do this

onPress={() => alert("clicked")}

it will work. Either pass onPress function through your data or bind your renderItem function in your constructor and then call

onPress={() => this.props.onPress()}
Related