使用Tailwind CSS和Next.js时边框颜色未发生变化

zf9nrax1  于 2023-02-08  发布在  其他
关注(0)|答案(3)|浏览(132)

当我把borderColor作为一个prop传递时,它不起作用,但是,当硬编码时,它可以正常工作。

export const SecondaryButton = ({
  borderColor = "secondary",
  text = "Button",
  to,
  hoverBg = "primary",
  hoverText = "white",
  hoverBorder = "primary",
  textColor = "white",
}) => {
  const cn = `hover:border-${hoverBorder} hover:bg-${hoverBg} hover:text-${hoverText} block px-[3rem] py-[1rem] rounded-md text-${textColor} font-medium border-2 mt-[2rem] transition-colors ease-in-out duration-300 border-${borderColor}`;
  return (
    <>
      <button
        className={cn}
        >
        {text}
      </button>
    </>
  );
};

父组件

const Right = () => (
  <div className="right px-[10rem] w-1/2">
    <h2 className="text-5xl custom-border-bottom">ABOUT US</h2>
    <p className="mt-[3rem] text-2xl">
     Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</p>
    
    <SecondaryButton text="Learn More" borderColor="blue" textColor="gray" />
  </div>
);

如下图所示,边框仍为浅灰色而非蓝色:

下图为放入硬编码值后的图像:

pxy2qtax

pxy2qtax1#

Tailwind生成的CSS文件将只包含它在扫描代码时识别的类,这意味着动态生成的类(例如border-${hoverBorder})将不包含在内。https://tailwindcss.com/docs/content-configuration#dynamic-class-names
您可以通过将完整的实用程序类名称传递给组件来修复此问题,以便它们包含在CSS中:

<SecondaryButton text="Learn More" borderColor="border-blue-500" textColor="text-gray" />

然后将它们直接应用到组件中:

const cn = `${textColor} ${borderColor} ...`;

另一个解决方案是,如果你有少量的可能颜色值,将它们添加到tailwind.config.js中Tailwind的安全列表中,这将强制Tailwind包含正确的实用程序类,无论它是否在你的代码中找到它们。

module.exports = {
  safelist: [
    'border-blue-500',
    'text-white',
    'text-gray',
  ]
}

有关安全列表的详细信息:https://tailwindcss.com/docs/content-configuration#safelisting-classes

voj3qocg

voj3qocg2#

刚刚找到有关命名约定的文档
https://tailwindcss.com/docs/content-configuration#dynamic-class-names

ulydmbyx

ulydmbyx3#

TailwindCSS不允许动态生成类。所以当你使用下面的代码来生成类时...

const cn = `hover:border-${hoverBorder} hover:bg-${hoverBg} hover:text-${hoverText} block px-[3rem] py-[1rem] rounded-md text-${textColor} font-medium border-2 mt-[2rem] transition-colors ease-in-out duration-300 border-${borderColor}`;

TailwindCSS不会将其作为有效的TailwindCSS类,因此不会生成必要的CSS。
尝试将cn的值替换为

const cn = "hover:border-" +hoverBorder+ " hover:bg-" +hoverBg+ "hover:text-" +hoverText+ " block px-[3rem] py-[1rem] rounded-md text-" +textColor+ " font-medium border-2 mt-[2rem] transition-colors ease-in-out duration-300 border-"+ borderColor;

相关问题