簡體   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