繁体   English   中英

你如何从 React 组件中提取特定的 TypeScript prop 类型?

[英]How do you extract a specific TypeScript prop type from a React component?

我正在创建自己的 Image 组件,并希望将 React 的图像组件ImageSourcePropType用于我的 source/previewSource 道具。

这是组件。

import React from 'react';
import { Image, ImageBackground } from 'react-native';

type ImageSourceProp = React.ComponentProps<typeof Image>.ImageSourcePropType; // HOW?

interface CachedImageProps {
  source: ImageSourceProp;
  previewSource: ImageSourceProp;
}

const CachedImage: React.FC<CachedImageProps> = ({ source, previewSource, ...remainingProps }) => {
  // console.log('TRIGGERED CachedImage')

  return (
    <ImageBackground source={previewSource|| source} fadeDuration={0} {...remainingProps}>
      <Image source={cachedSource} fadeDuration={0} {...remainingProps} />
    </ImageBackground>
  );
};

export default CachedImage;

我如何获得ImageSourcePropType

好的,想通了这一点。 有两种方法可以做到。

  1. 通过名称访问。

     type ImageSourcePropType = React.ComponentProps<typeof Image>['source'];
  2. 通过import访问。

     import { ImageSourcePropType } from 'react-native';

    (帽子提示@kschaer)

暂无
暂无

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

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