React Native报错:文本字符串需在<Text>组件中渲染,求协助
解决React Native "Text Strings must be rendered within a component" 错误
错误根源
React Native 要求所有文本内容必须包裹在 <Text> 组件内,不能直接在 <View> 等非文本容器下渲染字符串。你的代码里存在两处触发该错误的问题:
{item.icon}直接放在<View>中:如果item.icon是字符串类型(比如纯文本图标、文字),会违反渲染规则。- 无效的
index.key:FlatList 的index参数没有key属性,index.key会返回undefined,属于无效代码,可能引发潜在问题。
修复步骤
1. 处理 item.icon 的渲染
如果 item.icon 是字符串,用 <Text> 组件包裹它;如果是图标组件(如 Ionicons、FontAwesome)则无需修改:
<Text>{item.icon}</Text>
2. 修正索引内容
将 index.key 替换为有效的索引值,比如 index.toString(),或者直接移除(因为 keyExtractor 已经用索引作为key)。
3. 处理可能为空的 item.title
为避免 item.title 为 undefined 时出现异常,添加默认值:
{item.title || ''}
修改后的完整代码
<FlatList horizontal showsHorizontalScrollIndicator={false} data={ModalData} renderItem={({item, index}) => { return ( <View style={{ flexDirection: 'row', marginBottom: 10, marginHorizontal: 10, }}> <View style={{ flexDirection: 'column', justifyContent: 'center', alignItems: 'center', }}> {/* 根据item.icon类型选择是否包裹Text */} <Text>{item.icon}</Text> <Text style={{ fontSize: 15, color: '#3B3B3B', fontFamily: fonts.UbuntuNormal, padding: 10, }}> {item.title || ''} {index.toString()} </Text> </View> </View> ); }} keyExtractor={(item, index) => index.toString()} />
额外提醒:检查 ModalData 数组的每一项,确认 item.icon 的类型——如果是图标组件(来自 react-native-vector-icons 等库),则不需要用 <Text> 包裹,直接保留 {item.icon} 即可。
内容的提问来源于stack exchange,提问作者Shazaib Ahmed
相关产品推荐
相关产品推荐

