使用“className”时,React 本机打字稿给我一个 TS 错误

squ*_*ish 7 typescript reactjs react-native tailwind-css

使用 React 一段时间了,但对 React Native 还很陌生。

我正在使用 tailwind 和https://tailwindcss-react-native.vercel.app/installation

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>
  );
}
Run Code Online (Sandbox Code Playgroud)

Tailwind 可以工作,文本是红色的,但是我在上面的类名下遇到 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)
Run Code Online (Sandbox Code Playgroud)

我遵循了 expo typescript 设置,我的 tsconfig 如下所示:

{
  "compilerOptions": {},
  "extends": "expo/tsconfig.base"
}
Run Code Online (Sandbox Code Playgroud)

小智 16

在应用程序的根级别创建一个文件“global.d.ts”并粘贴此行

/// <reference types="nativewind/types" />
Run Code Online (Sandbox Code Playgroud)

包含此文件后,TypeScript 错误将消失,并且“className”属性工作得很好。


Rok*_*kas 14

我遇到了同样的问题,包含类型的最简单的解决方法是创建一个新app.d.ts文件并添加引用类型的三斜杠指令,如下所示:

/// <reference types="nativewind/types" />
Run Code Online (Sandbox Code Playgroud)

如果这不能解决您的问题,要消除红线,您可以 @ts-nocheck在文件顶部添加。(免责声明,此解决方案不能解决问题,只是通过禁用特定文件的 TS 检查来消除警告)


fik*_*tra 9

默认情况下,tailwindcss-react-native 快速启动设置不包括对 TypeScript 的支持。但是,文档提到了如何添加它:

创建一个文件(例如 src/tailwindcss-react-native.d.ts)并粘贴此行

import "tailwindcss-react-native/types.d";
Run Code Online (Sandbox Code Playgroud)

包含此文件后,TypeScript 错误将消失。


小智 -2

React NativeView和组件仅Text不接受classNameprop 。style

检查参考: https: //reactnative.dev/docs/text