React Native双FlatList实现两列布局时第二列props数据无法渲染求助
问题根因
- FlatList的
data属性仅支持数组类型的数据源,你给第二列FlatList传入的props是包含各字段值的对象,不符合格式要求,所以无法正常渲染 - 即使你将对象转为数组,也需要保证值的顺序和第一列的标签顺序完全一致,否则会出现标签和值错位的问题
修复方案
你只需要在DetailsInfo组件内,按照labels的顺序把对应的值提取为数组,作为第二列FlatList的数据源即可,修改后的核心代码如下:
import { View, FlatList, StyleSheet } from 'react-native'; // 假设AppText是你自定义的全局文本组件 const AppText = ({style, children}) => <Text style={style}>{children}</Text> const labels = [ "Height:", "Gender:", "Mass:", "Hair Color:", "Eye Color:", "Birth Year:", ]; // 新增标签和props字段的映射关系 const labelKeyMap = { "Height:": "height", "Gender:": "gender", "Mass:": "mass", "Hair Color:": "hair_color", "Eye Color:": "eye_color", "Birth Year:": "birth_year", }; function PeopleDetails(props) { const { name, height, gender, mass, hair_color, eye_color, birth_year } = props.route.params; return ( <View style={{flex: 1}}> <DetailsInfo height={height} gender={gender} mass={mass} hair_color={hair_color} eye_color={eye_color} birth_year={birth_year} /> </View> ); } const LabelView = ({ label }) => ( <View> <AppText style={styles.labelStyle}>{label}</AppText> </View> ); const LabelDataView = ({ labelData }) => ( <View> <AppText style={styles.labelDataStyle}> {labelData} </AppText> </View> ); const DetailsInfo = (props) => { // 按照标签顺序生成对应的值数组 const valueList = labels.map(label => props[labelKeyMap[label]]); return ( <View style={{ flex: 1, flexDirection: "row" }}> <FlatList style={{ flex: 1 }} data={labels} renderItem={({ item }) => <LabelView label={item} />} keyExtractor={(item) => item} scrollEnabled={false} /> <FlatList style={{ flex: 1 }} data={valueList} renderItem={({ item }) => <LabelDataView labelData={item} />} // 用索引做key避免值重复时报错 keyExtractor={(item, index) => String(index)} scrollEnabled={false} /> </View> ) }; const styles = StyleSheet.create({ labelStyle: { paddingTop: 5, marginLeft: 25, }, labelDataStyle: { paddingTop: 5, color: "gold", textTransform: "uppercase", textAlign: "left", }, });
额外优化建议
可以直接使用单个FlatList实现该布局,避免两个列表滚动不同步的问题:
const DetailsInfo = (props) => { // 直接把标签和值拼成单个数组作为数据源 const listData = labels.map(label => ({ label, value: props[labelKeyMap[label]] })) return ( <FlatList data={listData} renderItem={({item}) => ( <View style={{flexDirection: 'row'}}> <View style={{flex:1}}> <AppText style={styles.labelStyle}>{item.label}</AppText> </View> <View style={{flex:1}}> <AppText style={styles.labelDataStyle}>{item.value}</AppText> </View> </View> )} keyExtractor={(item) => item.label} /> ) }
内容的提问来源于stack exchange,提问作者mac4code
相关产品推荐
相关产品推荐

