我的FlatList是无状态组件,当按下项目时,我想通过调用方法“ handleOnPress”来处理onPress。我该怎么做 ??
以下是示例代码。
`
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>
)
}
`
答案 0 :(得分:2)
您的代码存在问题,这是onPress={props.onPress}
,您的renderItem
函数不知道(props)它所知道的只是传递给它的item参数。
如果您这样做
onPress={() => alert("clicked")}
它将起作用。通过数据传递onPress函数或将renderItem
函数绑定到构造函数中,然后调用
onPress={() => this.props.onPress()}
答案 1 :(得分:1)
您可以尝试一下吗?
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>
)
}
请注意这两个链接。
https://facebook.github.io/react-native/docs/flatlist
TouchableWithoutFeedback with custom component inside doesn't fires onPress callback
区别在于,将回调作为参数并添加了View层。