gpt4 book ai didi

reactjs - 如何在 React 中引用组件的 props?

转载 作者:搜寻专家 更新时间:2023-10-30 21:45:41 24 4
gpt4 key购买 nike

我有一个组件可以接受另一个组件作为 Prop 。无论它有什么其他 Prop ,它也会将它们传递给子组件。这就是它的样子:

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 只会接受某种类型的 props。这并不理想,因为有时我需要传递不一定与该签名匹配的组件。

我可能只写 ComponentType<any> ,但那太松了。我希望能够写出类似 ComponentType<Component['props']> 的东西,但据我所知,没有这样的事情。

有没有办法引用组件 Prop 类型?还是我需要手动传递泛型类型才能实现?

最佳答案

为响应 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>>;

它引用组件 Prop 的类型。您应该能够使用以下新类型之一实现所需的界面:

interface FormGroupProps {
label: string;
name: string;
Component: React.ComponentProps<typeof Component>;
}

如果您想避免到处导出 prop 接口(interface),或者从不导出它们的库中提取 props 接口(interface),这将非常方便。此外,与 Component['props'] 不同,它也适用于功能组件。

关于reactjs - 如何在 React 中引用组件的 props?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55484676/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com