简体   繁体   English

如何重新定义 React class 道具的类型

[英]How to redefine type for React class prop

I´m using Avatar from react-native-elements and the ImageComponent prop is typed as React.ComponentClass (IntelliSense report type React.ComponentClass<{}, any> )我正在使用来自react-native-elementsAvatar ,并且 ImageComponent 道具的类型为 React.ComponentClass (IntelliSense 报告类型React.ComponentClass<{}, any>

When using a functional component (with prop key) I get red squiggles under ImageComponent:当使用功能组件(带有道具键)时,我在 ImageComponent 下得到红色曲线:

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

Type '() => JSX.Element' is not assignable to type 'ComponentClass<{}, any>'.ts(2769)

AvatarImage:头像图片:

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

How can I fix this typescript error?如何修复此 typescript 错误?

I´ve tried to define a new class/interface that extend Avatar/AvatarProps:我试图定义一个扩展 Avatar/AvatarProps 的新类/接口:

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

  class MyAvatar extends Avatar<MyAvatarProps> {}

I get typescript error Type 'Avatar' is not generic.ts(2315)我收到 typescript 错误Type 'Avatar' is not generic.ts(2315)

How do I extend Avatar with MyAvatarProps when it's not generic?当它不是通用的时,如何使用 MyAvatarProps 扩展 Avatar?

Or is there other/better ways to handle this?还是有其他/更好的方法来处理这个?

Update:更新:

See my answer below请看下面我的回答

I got around the issue with a simple TS cast:我用一个简单的 TS cast 解决了这个问题:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM