【发布时间】:2021-04-21 08:10:11
【问题描述】:
我正在尝试使用样式组件创建一个按钮组件,该组件接受一个可以是 ComponentType | string 的道具 as 当我尝试另一个名为 skin 或 size 的道具时,我收到错误 No overload matches this call。我用谷歌搜索了我在阳光下能想到的东西。我已经尽我所能。我最初没有在样式组件中使用attrs,但在谷歌搜索了几个小时后,我认为我需要使用它但不确定。我错过了什么?
这里是 Button 组件:
const Button: FunctionComponent<FullProps> = ({
as,
children,
skin = "primary",
size = "medium",
...props,
}) => {
return (
<Component
as={as}
size={size}
skin={skin}
{...props}
>
{children}
</Component>
);
};
这是 FullProps 类型,它包含所有道具,但我正在尝试将其减少到最小的问题:
export type FullProps = {
as?: ComponentType | string;
isFullWidth?: boolean;
disabled?: boolean;
shadow?: ShadowStep;
size?: Size;
skin?: Skin;
theme?: Theme;
type?: HtmlButtonType;
href?: string;
onClick?: () => void;
children?: ReactNode;
id?: string;
loadingConfig?: LoadingConfig;
icon?: IconConfig;
};
我知道在使用样式化组件时,您应该使用道具forwardedAs 向下传递as 值。如果我只有一个简单的组件,那部分就可以工作:
const DemoALink = styled(Button)`
color: white;
background: #fb6058;
height: 4rem;
width: 100%;
display: flex;
justify-content: center;
align-items: center;
`;
这是正在使用的样式化组件:
<DemoALink forwardedAs="a" skin="primary">
Testings
</DemoALink>
这是组件的样式:
export const Button = styled.button.attrs<FullProps>(
({ disabled, as, type }: FullProps) => ({
type: as === "button" && type ? type : undefined,
disabled,
})
// )<Required<FullProps> & { children: ReactNode }>`
)<Required<FullProps> & { children: ReactNode }>`
${baseStyles};
${({ skin, theme }) => getVariant({ skin, theme })}
padding-top: ${getHeight};
padding-bottom: ${getHeight};
box-shadow: ${shadow};
width: ${({ isFullWidth }: { isFullWidth: boolean }) =>
isFullWidth ? "100%" : "auto"};
`;
【问题讨论】:
标签: javascript typescript styled-components