我有一个可以接受另一个组件作为道具的组件。不管它有其他什么道具,它都会将它们传递给子组件。那就是它的样子:
interface FormGroupProps extends BasicInputProps<any> {
label: string
name: string
Component: ComponentType<BasicInputProps<any>>
}
export const FormGroup: SFC<FormGroupProps> = ({
label,
Component,
...props
}) => (
<RBSFormGroup>
<Label>{label}</Label>
<Component {...props} />
</RBSFormGroup>
)
您可以看到,在FormGroupProps
我告诉TS的情况下,Component只接受某种类型的道具。这是不理想的,因为有时我需要传递不一定与该签名匹配的组件。
我可能会写ComponentType<any>
,但这太宽松了。我希望能够编写类似的内容ComponentType<Component['props']>
,但据我所知没有这样的东西。
有没有一种方法可以引用元件props类型?还是我需要手动传递一个泛型来实现?
为@types/react
响应React 16.6而引入的新类型包括以下类型:
type ComponentProps<T extends keyof JSX.IntrinsicElements | JSXElementConstructor<any>> =
T extends JSXElementConstructor<infer P>
? P
: T extends keyof JSX.IntrinsicElements
? JSX.IntrinsicElements[T]
: {};
type ComponentPropsWithRef<T extends ElementType> =
T extends ComponentClass<infer P>
? PropsWithoutRef<P> & RefAttributes<InstanceType<T>>
: PropsWithRef<ComponentProps<T>>;
type ComponentPropsWithoutRef<T extends ElementType> = PropsWithoutRef<ComponentProps<T>>;
其中引用了组件的道具类型。您应该能够使用以下新类型之一实现所需的界面:
interface FormGroupProps {
label: string;
name: string;
Component: React.ComponentProps<typeof Component>;
}
如果您要避免在各处导出prop接口,或者要从不导出prop接口的库中提取prop接口,这将非常方便。另外,与不同Component['props']
,它也适用于功能组件。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句