我有一个组件可以接受另一个组件作为道具。无论它有什么其他道具,它也会将它们传递给子组件。这就是它的样子:
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组件只接受某种类型的道具。这并不理想,因为有时我需要传递不一定与该签名匹配的组件。
我可能只是写ComponentType<any>
,但那太松了。我希望能够写出像ComponentType<Component['props']>
这样的东西,但据我所知,没有这样的东西。
有没有办法引用组件道具类型?或者我是否需要手动传递泛型类型才能实现?
针对React 16.6引入@types/react
的新类型包括以下类型:
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接口,或者从不导出它们的库中提取props接口,这非常方便。此外,与Component['props']
不同,它也适用于功能组件。