【发布时间】:2021-09-17 18:51:34
【问题描述】:
学习打字稿。 我正在尝试将类型添加到接受包装器组件的反应组件并将其余道具转发到包装器组件。但出现以下错误:
Type 'Pick<DirectProps<WrapperProps> & WrapperProps, Exclude<keyof WrapperProps, "as">> & { children: string; }' is not assignable to type 'IntrinsicAttributes & WrapperProps & { children?: ReactNode; }'.
Type 'Pick<DirectProps<WrapperProps> & WrapperProps, Exclude<keyof WrapperProps, "as">> & { children: string; }' is not assignable to type 'WrapperProps'.
'WrapperProps' could be instantiated with an arbitrary type which could be unrelated to 'Pick<DirectProps<WrapperProps> & WrapperProps, Exclude<keyof WrapperProps, "as">> & { children: string; }'
我无法解决。
小例子:
interface DirectProps<Props = unknown> {
as?: string | React.ComponentType<Props>;
}
function GenericComponent<Props = unknown>({
as: Component = "div",
...props
}: DirectProps<Props> & Props): JSX.Element {
return <Component {...props}>Here goes children</Component>;
}
这样使用:
{/* Render as div */}
<GenericComponent onClick={() => console.log("Click")} />
{/* Render as link */}
<GenericComponent<React.AnchorHTMLAttributes<HTMLAnchorElement>>
as="a"
href="https://stackoverflow.com"
target="_blank"
/>
我准备了代码框示例: https://codesandbox.io/s/sweet-hofstadter-2zzbe?file=/src/App.tsx
我会永远感激你的帮助
【问题讨论】:
标签: reactjs typescript