React Native中如何在FlatList内针对特定字段展示不同颜色与文本
React Native FlatList 性别展示逻辑实现方案
原有代码中重复渲染了两次性别文本,我们合并为一个做统一条件处理即可,无需修改数据请求相关逻辑,修改后的完整代码如下:
const API_ENDPOINT = `https://randomuser.me/api/?seed=1&page=1&results=20`; const [fullData, setFullData] = useState([]); const [products, setProducts] = useState([]); useEffect(() => { fetch(API_ENDPOINT) .then((response) => response.json()) .then((response) => { setProducts(response.results); setFullData(response.results); }); }, []); <FlatList data={products} keyExtractor={(item) => item.email} renderItem={({ item }) => ( <View style={styles.listItem}> <View style={styles.metaInfo}> <Text style={styles.title}>{item.name.first}</Text> <Text style={[ styles.title, item.gender === 'male' ? {color: 'blue'} : {} ]} > {item.gender === 'female' ? 'oops' : item.gender} </Text> </View> </View> )} />
- 代码中通过条件判断实现需求:gender为male时叠加蓝色样式,gender为female时替换显示文本为「oops」
- 你可以自行替换
{color: 'blue'}为你需要的特殊颜色值
内容的提问来源于stack exchange,提问作者John Ocean
相关产品推荐
相关产品推荐

