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>
)
}
`
The ItemSeparatorComponent prop of FlatList is used to implement the separator between the elements of the list. To perform the click event on list items, we use onPress prop to Text.
If you are using a FlatList in React Native, there's a chance you will want to use the scrollToIndex function to scroll to a certain item's index. Unfortunately, this function is a lot easier to use with fixed item heights where it is easy to implement the required getItemLayout function.
flatlist-simple By passing extraData={selectedId} to FlatList we make sure FlatList itself will re-render when the state changes. Without setting this prop, FlatList would not know it needs to re-render any items because it is a PureComponent and the prop comparison will not show any changes.
Use getItemLayout If all your list item components have the same height (or width, for a horizontal list), providing the getItemLayout prop removes the need for your FlatList to manage async layout calculations. This is a very desirable optimization technique.
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()}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With