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

TSX文件中Text无法作为JSX组件使用的问题求助

解决 "Text cannot be used as a JSX component" 错误

问题根源

你在React Native的TSX文件里碰到这个错误,核心原因是依赖冲突和类型配置不匹配:

  • React Native项目不需要react-dom(这是Web React专属依赖),同时安装react和react-dom会打乱TS对JSX组件的类型校验逻辑。
  • 缺少适配React 17的React Native类型定义,或类型版本与现有依赖不兼容。

具体修复步骤

1. 移除多余的react-dom依赖

React Native完全不依赖react-dom,直接卸载:

npm uninstall react-dom
# 用yarn的话:
yarn remove react-dom

2. 安装匹配版本的React Native类型定义

确保@types/react-native版本和React 17.0.2兼容,推荐安装0.66.x系列(对应React 17的React Native稳定版):

npm install @types/react-native@^0.66 --save-dev
# 用yarn的话:
yarn add @types/react-native@^0.66 --dev

3. 修正tsconfig.json关键配置

调整TS配置以适配React Native,重点修改jsx字段:

{
  "compilerOptions": {
    "target": "esnext",
    "module": "commonjs",
    "lib": ["es2017"],
    "allowJs": true,
    "jsx": "react-native", // 必须设为react-native,不能用web端的react-jsx
    "noEmit": true,
    "isolatedModules": true,
    "strict": true,
    "moduleResolution": "node",
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "resolveJsonModule": true
  },
  "exclude": [
    "node_modules",
    "babel.config.js",
    "metro.config.js",
    "jest.config.js"
  ]
}

4. 修复代码里的隐藏问题

注意:React Native的Text组件本身不支持onPress事件,需要用Pressable或TouchableOpacity包裹,同时给navigation补上类型定义(符合TS要求):

import * as React from 'react';
import { View, Text, Pressable } from 'react-native';
import type { NativeStackNavigationProp } from '@react-navigation/native-stack';

// 定义路由参数类型,后续对接RootState也能复用
type RootStackParamList = {
  Chat: undefined;
  ChatScreen: undefined;
};

type ChatScreenProps = {
  navigation: NativeStackNavigationProp<RootStackParamList, 'ChatScreen'>;
};

export default function ChatScreen({ navigation }: ChatScreenProps) {
  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Pressable onPress={() => navigation.navigate('Chat')}>
        <Text style={{ fontSize: 26, fontWeight: 'bold' }}>Chat Screen</Text>
      </Pressable>
    </View>
  );
}

5. 清除缓存重启服务

最后清除Metro缓存,避免旧配置残留:

npx react-native start --reset-cache

验证修复

重新运行项目:

npx react-native run-android
# 或iOS端:
npx react-native run-ios

TS的类型错误应该会完全消失,组件能正常渲染。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 17:45:42