我对类型记录相当陌生,当我将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.