简体   繁体   English

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

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

I'm creating my own Image component and want to reuse React's image component ImageSourcePropType for my source/previewSource props.我正在创建自己的 Image 组件,并希望将 React 的图像组件ImageSourcePropType用于我的 source/previewSource 道具。

Here's the component.这是组件。

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;

How do I get the ImageSourcePropType ?我如何获得ImageSourcePropType

OK, figured this one out.好的,想通了这一点。 There are two ways to do it.有两种方法可以做到。

  1. Access via name.通过名称访问。

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

     import { ImageSourcePropType } from 'react-native';

    (hat tip @kschaer) (帽子提示@kschaer)

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

相关问题 如何使用defaultProps从React组件中提取道具类型? - How do you extract prop types from a React Component with defaultProps? 你如何键入一个作为道具传递给组件的 useState 钩子,typescript + react - How do you type a useState hook that is being passed as a prop to a component, typescript+react 如何在组件(React + TypeScript)中输入链接属性? - How to type link prop in component (React + TypeScript)? 如何为React props定义TypeScript类型,只有在将prop A传递给组件时,才会接受prop B? - How do I define a TypeScript type for React props where prop B is only accepted if prop A is passed to a component? 如何将组件的类型断言为 prop? - How do you assert the type of a component as prop? 需要特定类型的功能组件作为带有 Typescript 的 React 中的道具 - Require a specific type of functional component as a prop in React with Typescript 多态组件 - 使用 Typescript 从 React 中的道具中选择类型 - Polymorphic component - selecting type from a prop in React with Typescript 如何在反应 typescript 中键入一个 function 组件的道具 - How to type a prop which is a function component in react typescript 限制 Typescript 中 React Component prop 的类型 - Restrict the type of React Component prop in Typescript 将 TypeScript 类型作为道具传递给 React 组件? - Pass a TypeScript Type as a prop to a React component?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM