我的平面列表是无状态组件,当按下项目时,我想通过调用方法"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>
)
}
'
你能试试这个吗?
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>
)
}
请注意那2个链接。
https://facebook.github.io/react-native/docs/flatlist
TouchableWithoutFeedback内部带有自定义组件不会在新闻回调时触发
区别在于,将回调作为参数并添加视图层。
你的代码问题是,onPress={props.onPress}
你的renderItem
函数不知道(props(它只知道传递给它的 item 参数。
如果你这样做
onPress={() => alert("clicked")}
它会起作用。要么通过数据传递 onPress 函数,要么在构造函数中绑定renderItem
函数,然后调用
onPress={() => this.props.onPress()}
<FlatList
style={styles.container}
data={props.data}
keyExtractor={item => item.id.toString()}
renderItem={ ({ item }) => (
<SomeComponent
title={item.title}
onPress={ () => pressHandler() }
/>
)}
/>
因此,基本上在"renderItem"中,您传递了将分配给每个"项目"迭代的组件。 例如,您有博客文章数据,"renderItem"组件将表示每个帖子(项目(的布局。
这意味着您可以在该组件上设置 onPress(例如
您甚至可以将参数传递给此处理程序,例如:
<FlatList
style={styles.container}
data={props.data}
keyExtractor={item => item.id.toString()}
renderItem={ ({ item }) => (
<SomeComponent
title={item.title}
onPress={ () => pressHandler(item.id) }
/>
)}
/>
请记住,您的数据对象需要具有此"id"或"_id"或"uid"或其他内容,但您肯定需要从"item"对象引用此"id",因为您正在迭代的每个数据实例都会自动映射到"item"对象。
一旦将其传递给子组件(SomeComponent/>(,您就可以访问如下内容:
export const SomeComponent = ({ title, onPress }) => {
return (
<Pressable onPress={onPress}>
[...some content here]
</Pressable>
);
};
您可以尝试其他方法,而不是可按,但我发现 onPress on View 可能无法正常工作,而"可按"在您的应用程序中将更具前瞻性。