React Native嵌套FlatList:如何从内层列表引用外层Item属性?
Solution for Accessing Outer FlatList Item in Nested FlatList
The core issue is variable shadowing—your inner FlatList's renderItem uses the same item variable name as the outer one, which overrides the outer reference. Here's how to fix it:
Step-by-Step Fix
- Rename the outer
FlatList'sitemto a distinct identifier (e.g.,sectionItem) in the renderItem destructuring. - Use this renamed variable inside the inner
FlatListto access the outer section'sorderproperty.
Corrected Code
<FlatList data={course.sections} keyExtractor={(section) => section.id} renderItem={({item: sectionItem}) => {/* Rename outer item to sectionItem */} <View> <Text>{sectionItem.order}. {sectionItem.title}</Text> <FlatList data={sectionItem.videos} keyExtractor={(video) => video.id} renderItem={({item: videoItem}) => {/* Rename inner item for clarity */} <Pressable onPress={() => navigation.navigate('Video Details' as never)}> <Text>{sectionItem.order}.{videoItem.order} {videoItem.title}</Text> </Pressable> } /> </View> } />
Why This Works
By renaming the outer item to sectionItem, you avoid overwriting the variable name in the inner scope. Since the inner renderItem function is a closure, it retains access to variables from the outer scope—including sectionItem.
You can also keep the inner item as item (no rename needed) and still access the outer value:
// Alternative: inner item remains 'item' renderItem={({item}) => <Pressable onPress={() => navigation.navigate('Video Details' as never)}> <Text>{sectionItem.order}.{item.order} {item.title}</Text> </Pressable> }
内容的提问来源于stack exchange,提问作者Shaimaa
相关产品推荐
相关产品推荐

