React Native中如何解析location对象下的flag与country子字段?
你只需要通过.访问符逐层获取location下的子属性即可,注意不要直接把对象类型的值放到Text组件内渲染,React Native不支持直接渲染普通对象。
方案1:确定item.location一定存在的场景
直接修改对应Text部分的取值即可,可根据需求拼接或者拆分展示两个子属性:
<View style={{ flexDirection: 'row' }}> <AntDesign name="flag" size={12} color="black" style={{ marginTop: 3, marginRight: 10 }} /> <Text style={styles.H1}>{item.name}</Text> <Text style={styles.H2}>{item.location.flag} {item.location.country}</Text> </View>
方案2:兼容item.location可能为空的场景
使用可选链操作符做兼容处理,避免location为undefined/null时触发属性读取报错:
<View style={{ flexDirection: 'row' }}> <AntDesign name="flag" size={12} color="black" style={{ marginTop: 3, marginRight: 10 }} /> <Text style={styles.H1}>{item.name}</Text> <Text style={styles.H2}>{item.location?.flag} {item.location?.country}</Text> </View>
如果需要把两个子属性放在不同的Text组件中分开排版,拆分取值即可:
<Text style={styles.H2}>{item.location?.flag}</Text> <Text style={styles.H2}>{item.location?.country}</Text>
内容的提问来源于stack exchange,提问作者Najeeb Gafar
相关产品推荐
相关产品推荐

