React Native横向FlatList异常求助:仅显示单卡且无法滑动
问题
视图中实现了两个FlatList,垂直FlatList运行完全正常,但横向FlatList出现异常:仅能显示一张卡片且无法滑动。已确认不是缺失flex-1的问题,项目使用Tailwind CSS,相关代码如下:
Home组件代码
const Home = () => { const renderItem = useCallback( ({ item, onpress }) => <VideoListItem onpress={onpress} item={item} />, [] ); return ( <> <SafeAreaView className="flex-1"> <KeyboardAvoidingView behavior={Platform.OS === "ios" ? "height" : undefined} keyboardVerticalOffset={100} > <View className="flex flex-row mx-6 my-2 px-3 py-3 justify-between items-center " style={styles.searchContainer} > <Image className="rounded-full" style={{ width: scale(30), height: scale(30) }} source={require("../assets/mlucas.jpg")} /> <Ionicons name="search-outline" size={scale(25)} color="px-2 bg-black border" /> </View> </KeyboardAvoidingView> <Text className="text-xl px-6 my-3"> Dernières vidéos</Text> <View style={{ flex: 1 }} className="px-6 mb-3"> {data && ( <> <FlatList horizontal={true} data={data} renderItem={renderItem} keyExtractor={(item) => item.title} /> </> )} </View> <Text className="text-xl px-6 my-3"> Toutes nos vidéos</Text> <View style={{ flex: 1 }} className="px-6"> {data && ( <FlatList showsVerticalScrollIndicator={false} data={data} renderItem={renderItem} keyExtractor={(item) => item.title} /> )} </View> </SafeAreaView> </>
VideoListItem组件代码
const VideoListItem = ({ item, onpress }) => { return ( <Pressable className=' bg-gray-200 border my-2 rounded-2xl' onPress={openVideoPage} style={styles.videoCard}> <View > <Image style={styles.thumbnail} className="rounded-t-2xl" source={{ uri: item.url_image || "" }} /> </View> <View style={styles.titleRow}> <View style={styles.midleContainer}> <Text className='text-black'style={styles.title}>{item.title}</Text> <Text style={styles.subtitle}> {item.User?.name || "No name"} </Text> </View> </View> </Pressable> ) }
解决办法
1. 给横向FlatList容器设置固定高度
外层的flex:1会让横向FlatList容器和下方垂直FlatList容器平分空间,导致横向列表高度不足,无法触发滑动。把容器的flex:1替换为固定高度:
<View className="px-6 mb-3" style={{ height: 220 }}> {data && ( <FlatList horizontal={true} data={data} renderItem={renderItem} keyExtractor={(item) => item.title} /> )} </View>
2. 给VideoListItem设置固定宽度
横向FlatList的子项默认会撑满容器宽度,导致只能显示一个。给子项添加固定宽度:
<Pressable className=' bg-gray-200 border my-2 rounded-2xl w-64' onPress={openVideoPage} style={styles.videoCard} > {/* 子组件内容 */} </Pressable>
或者在StyleSheet中设置:
const styles = StyleSheet.create({ videoCard: { width: 250, // 按需调整 // 其他样式 } })
3. 优化FlatList属性
- 确保
keyExtractor使用唯一值(如果title有重复,改用item的id):
keyExtractor={(item) => item.id || item.title}
- 可选添加
showsHorizontalScrollIndicator={false}隐藏横向滚动条,同时确认data数组确实包含多个元素。
4. 调整外层布局优先级
如果需要保留flex布局,给横向FlatList容器添加flexShrink:0避免被垂直列表挤压:
<View style={{ flexShrink: 0 }} className="px-6 mb-3"> {/* 横向FlatList */} </View>
内容的提问来源于stack exchange,提问作者mdc123
相关产品推荐
相关产品推荐

