我对类型记录相当陌生,当我将TS与样式组件结合使用时(特别是当我尝试使用样式组件时),我会遇到一个奇怪的错误:
下面是我的道具类型声明:
export interface ButtonProps {
primary: boolean;
size: "small" | "medium" | "large";
label: string;
onClick: (
event: React.MouseEvent<HTMLButtonElement, MouseEvent>
) => void;
};
下面是我创建样式组件的地方:
const StyledButton = styled.button<ButtonProps>`
${ButtonStyles.buttonBase};
${({ primary }) => primary ? ButtonStyles.primary : ButtonStyles.secondary}
${({ size }) => ButtonStyles[size]}
`
下面是主要的组件实现,在这里我尝试使用我的样式组件:
const Button = ({
primary,
size,
onClick,
label
}: ButtonProps) => {
return (
<StyledButton //<== error occurs here
primary={primary}
size={size}
onClick={onClick}
>
{label}
</StyledButton>
);
}
我的默认道具声明:
Button.defaultProps = {
primary: false,
size: "medium"
}
下面是VS代码给我的错误(相当长,很详细):
No overload matches this call.
Overload 1 of 2, '(props: { form?: string | undefined; label: string; slot?: string | undefined; style?: CSSProperties | undefined; title?: string | undefined; ref?: ((instance: HTMLButtonElement | null) => void) | RefObject<...> | null | undefined; ... 264 more ...; size: "small" | ... 1 more ... | "large"; } & { ...; } & { ...; }): ReactElement<...>', gave the following error.
Property 'label' is missing in type '{ children: string; primary: boolean; size: "small" | "medium" | "large"; onClick: (e: MouseEvent<HTMLButtonElement, MouseEvent>) => void; }' but required in type '{ form?: string | undefined; label: string; slot?: string | undefined; style?: CSSProperties | undefined; title?: string | undefined; ref?: ((instance: HTMLButtonElement | null) => void) | RefObject<...> | null | undefined; ... 264 more ...; size: "small" | ... 1 more ... | "large"; }'.
Overload 2 of 2, '(props: StyledComponentPropsWithAs<"button", any, ButtonProps, never, "button", "button">): ReactElement<StyledComponentPropsWithAs<"button", any, ButtonProps, never, "button", "button">, string | JSXElementConstructor<...>>', gave the following error.
Property 'label' is missing in type '{ children: string; primary: boolean; size: "small" | "medium" | "large"; onClick: (e: MouseEvent<HTMLButtonElement, MouseEvent>) => void; }' but required in type '{ form?: string | undefined; label: string; slot?: string | undefined; style?: CSSProperties | undefined; title?: string | undefined; ref?: ((instance: HTMLButtonElement | null) => void) | RefObject<...> | null | undefined; ... 264 more ...; size: "small" | ... 1 more ... | "large"; }'.ts(2769)
Button.tsx(17, 3): 'label' is declared here.
Button.tsx(17, 3): 'label' is declared here.
问题似乎在于打印文本理解标签支柱,但由于对TS缺乏经验,我很难理解问题并找到解决方案。
当我更改ButtonProps接口使label是可选的时,错误就消失了,所以看起来我传递标签时没有保证它会有一个非空值。
但是,如果我将它恢复为一个必需的值,然后在Button.defaultProps中传递一个标签的默认值(保证它总是有一个非空值),那么错误不会消失。
我希望能解释一下这里发生了什么,解决这个错误的正确方法,以及在将来避免这个问题的任何重构。
发布于 2022-04-11 06:06:15
如果将label
作为children
支柱传递,则需要显式地传递它:
<StyledButton
primary={primary}
size={size}
onClick={onClick}
label={label}
/>;
https://stackoverflow.com/questions/71821940
复制相似问题