我正在构建一个应用程序,并希望拥有Primary、Secondary和Thirdy按钮,我不想创建3个相同但具有不同样式组件的独立组件,所以我想像下面的代码一样有条件地显示正确的标记,但我收到一个错误JSX元素类型"ButtonStyles"没有任何构造或调用签名。我做错了什么?感谢
import React from "react";
import styled from "styled-components";
const PrimaryStyles = styled.button`
width: 26rem;
height: 5rem;
background-image: ${({ theme }) => theme.gradients.ry};
border: none;
border-radius: 4px;
color: ${({ theme }) => theme.black};
font-size: 2rem;
box-shadow: 3px 3px 30px ${({ theme }) => theme.red + "70"};
cursor: pointer;
padding: 0 1rem;
`;
const SecondaryStyles = styled.button``;
const TertiaryStyles = styled.button`
border: none;
background: none;
color: ${({ theme }) => theme.grey};
`;
interface IProps {
type: "button" | "reset" | "submit";
children: React.ReactNode;
onClick: React.MouseEventHandler<HTMLButtonElement>;
primary?: boolean;
secondary?: boolean;
tertiary?: boolean;
}
export const Button: React.FC<IProps> = ({
children,
onClick,
type,
primary = true,
secondary,
tertiary,
}) => {
const ButtonStyles = primary
? PrimaryStyles
: secondary
? SecondaryStyles
: tertiary
? TertiaryStyles
: null;
return (
<ButtonStyles type={type} onClick={onClick}>
{children}
</ButtonStyles>
);
};
这是因为这个逻辑:
const ButtonStyles = primary
? PrimaryStyles
: secondary
? SecondaryStyles
: tertiary
? TertiaryStyles
: null;
如果不是primary
、secondary
或tertiary
,则为null
。所以你的代码会将ButtonStyles
设置为NULL
,然后你就不能这样做了:
return (
<ButtonStyles type={type} onClick={onClick}>
{children}
</ButtonStyles>
);
对此的解决方案是删除NULL
选项,类似于:
const ButtonStyles = primary
? PrimaryStyles
: secondary
? SecondaryStyles
: TertiaryStyles;
另一种避免三元条件运算符的方法是这样做:
- 创建一个包含以下3个样式选项的对象:
interface IButtonStyles {
[key: string]: StyledComponent<"button", any, {}, never>;
}
const buttonStyleTypes: IButtonStyles = {
primary: PrimaryStyles,
secondary: SecondaryStyles,
tertiary: TertiaryStyles,
};
- 将您的IProp更改为类似的内容:
interface IProps {
type: "button" | "reset" | "submit";
children: React.ReactNode;
onClick: React.MouseEventHandler<HTMLButtonElement>;
styleType?: string;
}
- 按钮组件:
const Button: React.FC<IProps> = ({
children,
type,
styleType = "primary",
}) => {
const ButtonStyles = buttonStyleTypes[styleType];
return <ButtonStyles type={type}>{children}</ButtonStyles>;
};
- 最后,您可以创建这样的按钮:
<Button type={"button"}>primary</Button>
<Button type={"button"} styleType='secondary'>secondary</Button>
<Button type={"button"} styleType='tertiary'>tertiary</Button>