【问题标题】:How to redefine type for React class prop如何重新定义 React 类道具的类型
【发布时间】:2021-01-10 12:51:06
【问题描述】:

我正在使用来自 react-native-elementsAvatar,并且 ImageComponent 道具的类型为 React.ComponentClass(IntelliSense 报告类型 React.ComponentClass<{}, any>

当使用功能组件(带有 prop 键)时,我在 ImageComponent 下得到红色曲线:

  <Avatar
    rounded
    size={c.styles.avatarSize}
    containerStyle={{ margin: c.styles.marginLRTB / 2 }}
    placeholderStyle={{ backgroundColor: colors.background }}
    ImageComponent={() => AvatarImage(key)}
  />

Type '() =&gt; JSX.Element' is not assignable to type 'ComponentClass&lt;{}, any&gt;'.ts(2769)

头像图片:

  const AvatarImage = (key: string) => (
    <FastImage
      style={{ width: '100%', height: '100%' }}
      source={sourcesState[key].category === 'In-app' ? avatars[key as QuotesListKeys] : { uri: sourcesState[key].imageUrl }}
    />
  );

如何解决这个打字稿错误?

我尝试定义一个扩展 Avatar/AvatarProps 的新类/接口:

  type MyAvatarProps = Omit<AvatarProps, 'ImageComponent'> & { ImageComponent: FC<{ key: string }> };

  class MyAvatar extends Avatar<MyAvatarProps> {}

我收到打字稿错误Type 'Avatar' is not generic.ts(2315)

如果不是通用的,我如何使用 MyAvatarProps 扩展 Avatar?

或者有其他/更好的方法来处理这个问题?

更新:

请看下面我的回答

【问题讨论】:

  • 如果AvatarImage(key) 返回JSX.Element,那么试试ImageComponent={AvatarImage(key)}
  • @RameshReddy 我收到类似的 TS 错误:“元素”不可分配给类型“ComponentClass”.ts(2769)。 ImageComponent 也需要箭头函数才能工作。
  • 基于这个reactnativeelements.com/docs/avatar/#imagecomponent,类型可以是一个元素,所以我不知道为什么它只需要一个类组件。
  • @RameshReddy 是的,这是真的。我可能会创建一个报告此问题的问题。无论如何,如果能用 typescript 来解决这个问题就好了。
  • 好的,在此之前,请确保您使用的是最新的稳定版本,并且您使用的不是不支持功能组件类型的旧版本。

标签: reactjs typescript react-native react-native-elements


【解决方案1】:

我通过一个简单的 TS 演员解决了这个问题:

ImageComponent={((() => AvatarImage(key)) as unknown) as ComponentClass<{}, any>}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-11
    • 1970-01-01
    • 2020-07-09
    • 1970-01-01
    相关资源
    最近更新 更多