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

React Native TypeScript使用className属性时出现TS类型报错

React Native接入tailwindcss-react-native后className属性TS报错解决

问题背景

有React使用经验,刚接触React Native开发,按照官方安装指引接入tailwindcss-react-native后,运行时Tailwind样式可正常生效(Text组件文本可正确显示为红色),但组件上的className属性始终存在TS类型报错。

测试组件代码

import { View, Text } from "react-native";
import React from "react";

export default function Navigation() {
  return (
    <View className="grid h-screen w-screen place-items-center">
      <Text className="text-red-800">Test</Text>
    </View>
  );
}

TS报错信息

No overload matches this call.
  Overload 1 of 2, '(props: ViewProps | Readonly<ViewProps>): View', gave the following error.
    Type '{ children: Element; className: string; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes<View> & Readonly<ViewProps> & Readonly<{ children?: ReactNode; }>'.
      Property 'className' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes<View> & Readonly<ViewProps> & Readonly<{ children?: ReactNode; }>'.
  Overload 2 of 2, '(props: ViewProps, context: any): View', gave the following error.
    Type '{ children: Element; className: string; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes<View> & Readonly<ViewProps> & Readonly<{ children?: ReactNode; }>'.
Property 'className' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes<Text> & Readonly<TextProps> & Readonly<{ children?: ReactNode; }>'.ts(2769)

当前tsconfig配置

已按照Expo官方TypeScript配置指引完成基础配置,当前配置如下:

{
  "compilerOptions": {},
  "extends": "expo/tsconfig.base"
}

解决步骤

  • 第一步:在项目根目录新建类型声明文件app.d.ts,写入以下内容,引入tailwindcss-react-native提供的原生组件类型补充声明:
/// <reference types="tailwindcss-react-native" />
import "tailwindcss-react-native/types.d";
  • 第二步:修改项目根目录的tsconfig.json,将tailwindcss-react-native的类型纳入编译范围,同时确保新建的声明文件被TS识别,调整后配置如下:
{
  "extends": "expo/tsconfig.base",
  "compilerOptions": {
    "types": ["tailwindcss-react-native"]
  },
  "include": [
    "**/*.ts",
    "**/*.tsx",
    "./app.d.ts"
  ]
}
  • 第三步:重启TS服务即可消除报错。如果使用VS Code,可通过快捷键唤起命令面板,执行TypeScript: Restart TS Server命令。

报错本质原因:React Native原生组件的默认类型定义不包含className属性,tailwindcss-react-native在运行时通过babel插件完成了className到style属性的转换,所以样式能正常生效,但如果没有正确加载库提供的类型补充声明,TS就会提示属性不存在的类型错误。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 22:45:44