typescript 如何以一种更干净的方式格式化tailwind类,以动态地重用样式?

t1qtbnec  于 2023-01-21  发布在  TypeScript
关注(0)|答案(1)|浏览(151)

我使这个可重复使用的徽章使用顺风CSS的徽章的颜色应该根据状态而改变。结果是非常不干净,我正在寻找一种方法来优化这一点。
我试过使用字符串文字来使样式更简洁,如下所示;
bg-${color}-100和其他类名称相同。显然,这不起作用,因为tailwind希望您传递一个完整的类名称,如bg-green-100。这意味着我必须有条件地检查每种颜色,如color === "green"? "bg-green-100" : "bg-red-100",这迫使您编写这么多的类,如果您有很多颜色 prop ,您正在检查。
这是整个组件的样子

import ctl from "@netlify/classnames-template-literals";
interface BadgeProps {
  color: string;
  status: string | boolean;
}

function Badge({ color, status }: BadgeProps) {
  return <span className={badgeStyle(color)}>{status}</span>;
}

const badgeStyle = (color: string) =>
  ctl(
   `
    ${
      color === "green"
        ? `bg-green-100 text-green-800  ${containerStyle} dark:bg-green-900 dark:text-green-300`
        : color === "red"
        ? `bg-red-100 text-red-800  ${containerStyle} dark:bg-red-900 dark:text-red-300`
        : color === "yellow"
        ? `bg-yellow-100 text-yellow-800  ${containerStyle} dark:bg-yellow-900 dark:text-yellow-300`
        : color === "blue"
        ? "bg-blue-100 text-blue-800  ${containerStyle} dark:bg-blue-900 dark:text-blue-300"
        : color === "indigo"
        ? `bg-indigo-100 text-indigo-800  ${containerStyle} dark:bg-indigo-900 dark:text-indigo-300`
        : color === "purple"
        ? `bg-purple-100 text-purple-800  ${containerStyle} dark:bg-purple-900 dark:text-purple-300`
        : color === "pink"
        ? `bg-pink-100 text-pink-800  ${containerStyle} dark:bg-pink-900 dark:text-pink-300`
        : color === "orange"
        ? `bg-orange-100 text-orange-800  ${containerStyle} dark:bg-orange-900 dark:text-orange-300`
        : color === "gray"
        ? `bg-gray-100 text-gray-800  ${containerStyle} dark:bg-gray-900 dark:text-gray-300`
        : color === "gray"
        ? `bg-gray-100 text-gray-800  ${containerStyle} dark:bg-gray-900 dark:text-gray-300`
        : ""
    }
   
    `
  );

const containerStyle = ctl(`
 font-medium mr-2 px-2.5 py-0.5 rounded  text-sm text-sm
  `);

export default Badge;
nvbavucw

nvbavucw1#

唯一的选择是根据文档将这些三元语句重新格式化为字典。Source

function Button({ color, children }) {
  const colorVariants = {
    blue: 'bg-blue-600 hover:bg-blue-500',
    red: 'bg-red-600 hover:bg-red-500',
  }

  return (
    <button className={`${colorVariants[color]} ...`}>
      {children}
    </button>
  )
}

相关问题