如何将道具传递给可重用组件中的变体

How to pass prop to variant in reusable component

那是我第一次尝试创建类似于 ui 框架的可重用组件。我使用顺风造型。我创建了按钮变体。主要的,次要的,破坏性的。它工作正常。但是,我想添加 select 组件颜色的功能。但是,我找不到解决方案或弄清楚如何将颜色传递给 BUTTON_VARIANT。

如何将颜色道具传递给 BUTTON_VARIANT?

import classNames from "classnames";

type ButtonVariant = `primary` | `secondary` | `destructive`;
type ColorVariant = "slate" | "red";

interface Props {
  children: any;
  variant?: ButtonVariant;
  className: any;
  color: ColorVariant;
}

const BUTTON_VARIANT: { [key in ButtonVariant]: String } = {
  destructive: `text-white bg-red-500 hover:bg-red-600 capitalize font-semibold`,
  primary: `text-white bg-blue-500 font-semibold hover:bg-blue-600 capitalize`,
  secondary: `text-blue-500 bg-blue-100 font-semibold capitalize hover:bg-blue-100 hover:text-blue-700`,
};

export const Button = ({
  children,
  variant = "primary",
  className,
  color,
}: Props) => {
  return (
    <button
      className={classNames(
        className,
        `rounded py-2 px-4`,
        BUTTON_VARIANT[variant],
        className
      )}
    >
      {children}
    </button>
  );
};

Button.defaultProps = {
  className: "",
  variant: "primary",
  color: "blue",
};

您需要从 BUTTON_VARIANT 的样式中取出所有涉及颜色(背景、边框、文本等)的 类,并创建一个 COLORS_VARIANT 对象。但是,请记住,这可能会使您的变体 属性 变得无用。使用红色主按钮或蓝色破坏性按钮毫无意义。

我建议,如果您想使用 color 作为变体,请将您的 variant 道具名称改为 color-agnostic,例如 solid|transparent|outline,等等