为什么 TypeScript 告诉我 NativeBase 的 Button 组件上不存在 属性 但仍然呈现它?

Why do TypeScript tell me that a property doesn't exist on Button Component from NativeBase but still renders it?

我在 React Native 项目上使用 NativeBase,当我 运行 我的 iPhone 上的应用程序使用 Xcode 时一切正常,TypeScript 告诉我 [= =31=] NativeBase Button 类型上不存在“onPress”。

为了简化这里是我的代码:

import { Button } from 'native-base';

...

<Button
  variant="ghost"
  colorScheme="blueGray"
  onPress={() => {
  console.log('Ok')
  }}
>

我得到的错误是:

Type '{ children: string; onPress: () => void; }' is not assignable to type 'IntrinsicAttributes & IButtonProps & { ref?: MutableRefObject | undefined; }'. Property 'onPress' does not exist on type 'IntrinsicAttributes & IButtonProps & { ref?: MutableRefObject | undefined; }'.ts(2322)

同样,代码工作正常,但在我的项目的每个文件中每个按钮都会出现一个错误,这很烦人。

我不太习惯 React Native 和 NativeBase,所以我找不到它抛出这个错误的原因。

我试着查看一下文件,看看是否可以在某处找到“onPress”属性,因为它正在工作并且在文档中,我发现根据 TS :

import type { PressableProps } from 'react-native';

Module '"react-native"' has no exported member 'PressableProps'.ts(2305)

我的问题是为什么 TS 告诉我 onPress 不存在,但我认为它可以以某种方式提供帮助,因为它看起来应该是 onPress 所在的位置。

typeScript 只是一个类型检查器,它在 运行 时间内不起作用。这意味着如果你没有将正确的类型放入你的组件中,所有代码都可以正常工作,因为“typeScript 只在编译阶段完成他的工作”。所以,如果您想解决该错误问题,请转到 typeScript 文档页面并了解如何将类型设置到您的组件中。之后,当您在 Button 组件中设置正确的类型(功能)时,所有错误消息都会消失。

创建全新安装后,我发现出于某种原因——可能是因为我进行了更新以及我现在没有使用很多组件——而 React-Native 的版本是 0 .64.X,类型在版本 0.62.X。

所以解决方案是更改package.json

中@types/react-native的版本

TypeScript 不知道 onPress 属性 的存在,但它仍然存在,所以我在 运行 应用程序上没有问题。由于我将类型更新为正确的版本,它不再告诉我 属性 不存在。