You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native Expo手机端运行报Text字符串需在<Text>组件内渲染错误如何解决

问题原因

报错Render Error : Text strings must be rendered within a <Text> Component的根源是两个适配问题,Expo浏览器端(RN Web)对写法容错性高,原生端严格遵循React Native渲染规则才会触发报错:

  1. 直接在TouchableOpacity组件内写入了Read文本字符串,没有用<Text>组件包裹
  2. 将仅适用于<Text>组件的样式(color、fontSize、fontFamily、textAlign、lineHeight)写在了TouchableOpacity的样式上,原生端不识别这类跨组件样式。

修复方案

按如下步骤修改代码即可:

  1. 调整renderItem函数里的TouchableOpacity结构,把文本内容包裹在<Text>组件内
  2. 拆分样式,把文本相关的样式移到<Text>对应的样式上,删除TouchableOpacity样式中的文本属性

修改后的核心代码片段:

// 修改renderItem函数
function renderItem({item}){
    const path = item.key;
    return (
        <View style={styles.container}>
            <View style={styles.square}>
                <Text style={styles.h1}>{item.title}</Text>
                <TouchableOpacity style={styles.button} onPress={() => navigation.navigate('Document', {path})}>
                    {/* 把Read文本放到Text组件里 */}
                    <Text style={styles.buttonText}>Read</Text>
                </TouchableOpacity>
            </View>
        </View>
    )
};

// 修改样式表
const styles = StyleSheet.create({
    container:{
        paddingLeft: 30,
        paddingRight:30,
        paddingTop:20,
        paddingBottom:10
    },
    square:{
        backgroundColor: 'white',
        borderRadius: 4,
        padding: 30,
        shadowColor: 'black',
        shadowRadius: 10,
        shadowOpacity: 1,
    },
    h1:{
        textAlign: 'left',
        fontFamily: 'Merriweather',
        fontSize: 30,
    },
    p: {
        textAlign: 'justify',
        fontFamily: 'Open Sans',
        fontSize: 15,
        color: '#C8C8C8',
        lineHeight: 18,
    },
    // 调整button样式,移除文本相关属性
    button: {
        backgroundColor: '#3EDD84',
        width: 90,
        borderRadius: 3,
        marginTop: 15,
        marginRight: 70,
        paddingVertical: 5,
        alignItems: 'center'
    },
    // 新增按钮文本的样式
    buttonText: {
        color: 'white',
        fontSize: 25,
        fontFamily: 'merriweather',
    }
});

额外优化提示:React Native的尺寸单位默认就是dp,不需要加px后缀,直接写数值即可,避免部分原生端解析异常。另外View组件不需要加display: 'flex',RN的布局默认就是Flex布局。

内容的提问来源于stack exchange,提问作者Tech Sagan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 19:36:01