React Native中基于JSON动态控制<Text>标签显隐及分类展示
在React Native中动态控制Text显示与隐藏并处理分类数据
嘿,这两个需求其实很好实现,我结合你给的JSON数据来一步步说明:
1. 动态控制标签的显示与隐藏
在React Native里,我们可以通过条件渲染来灵活控制组件的显示和隐藏。核心思路就是根据数据状态(比如category数组是否为空)来决定要不要渲染对应的<Text>组件。常用的两种写法:
- 利用
&&短路求值:当条件为真时,才渲染后面的组件 - 使用三元表达式:适合处理更复杂的条件分支场景
2. 遍历JSON数据并提取分类title
针对你提供的商家JSON数据,我们需要遍历每个商家对象,再检查它的category数组:如果数组里有对象,就提取title字段并按「Category: [对应title值]」的格式展示;如果数组为空,就不显示分类相关的Text。
完整代码示例
import React from 'react'; import { View, Text, StyleSheet } from 'react-native'; const BusinessList = () => { // 你提供的商家JSON数据 const businessData = [ {"id":32156465,"b_name":"KFC","website":"kfc.com","category":[]}, {"id":87985645,"b_name":"Pizza Hut","website":"pizzahut.com","category":[{"id":"357","title":"Pizza"}]}, {"id":78956465,"b_name":"Mc Donalds","website":"mcdonalds.com","category":[{"id":"951","title":"Burger"}]}, {"id":32136556,"b_name":"Eagle Boys Pizza","website":null,"category":[]} ]; return ( <View style={styles.container}> {businessData.map(business => ( <View key={business.id} style={styles.businessCard}> <Text style={styles.businessName}>{business.b_name}</Text> {/* 动态显示网站:只有website不为null时才渲染 */} {business.website && <Text style={styles.website}>Website: {business.website}</Text>} {/* 动态显示分类:只有category数组非空时才渲染 */} {business.category.length > 0 && ( <View style={styles.categoryWrap}> {business.category.map(category => ( <Text key={category.id} style={styles.categoryText}> Category: {category.title} </Text> ))} </View> )} </View> ))} </View> ); }; const styles = StyleSheet.create({ container: { padding: 16, flex: 1, }, businessCard: { marginBottom: 16, padding: 12, borderWidth: 1, borderColor: '#eee', borderRadius: 8, }, businessName: { fontSize: 18, fontWeight: 'bold', marginBottom: 8, }, website: { fontSize: 14, color: '#666', marginBottom: 8, }, categoryWrap: { marginTop: 8, }, categoryText: { fontSize: 14, color: '#2ecc71', }, }); export default BusinessList;
代码说明
- 用
map遍历每个商家对象,给每个商家卡片设置唯一的key(用business.id保证唯一性) - 网站字段通过
business.website && <Text>...</Text>实现动态显示:如果website不为null或undefined,就渲染这段Text - 分类部分先判断
business.category.length > 0,只有数组有内容时才渲染分类组件;再用map遍历每个分类对象,提取title按要求格式展示
这样就能完美实现你要的两个需求啦!
内容的提问来源于stack exchange,提问作者iOSDev
相关产品推荐
相关产品推荐

