Tailwind 自定义颜色在 Next.js 项目中不起作用[重复]

2024-03-04

当我分配给变量并使用它时,tailwind.config.js 中配置的自定义颜色不起作用,如下所示。

其中button.colour =“custom-blue”(颜色数据从cms获取并可以在cms中设置)

<button class="inline-block px-6 py-2.5 bg-${button.colour} text-custom-dark-blue font-medium text-sm leading-tight rounded shadow-md hover:bg-white hover:border-2 border-custom-blue hover:text-${button.colour}">Submit</button>

但下面的代码工作得很好。

<button class="inline-block px-6 py-2.5 bg-custom-blue text-custom-dark-blue font-medium text-sm leading-tight rounded shadow-md hover:bg-white hover:border-2 border-custom-blue hover:text-custom-blue">Submit</button>

tailwind.config.js 文件:

module.exports = {
  content: [
    './pages/**/*.{js,ts,jsx,tsx}',
    './components/**/*.{js,ts,jsx,tsx}'
  ]
  ,
  theme: {
    extend: {
      colors: {
        'custom-blue':'#4AD7D1',
       },
    },
  
  },
  plugins: [],
  important: true
}

如何解决这个问题?


在本节下docs https://tailwindcss.com/docs/content-configuration#dynamic-class-names:

正如深入类检测中所述,Tailwind 实际上并不运行您的源代码,也不会检测动态构造的类名。

正如我的评论所提到的,Tailwind 的类清除器 (PurgeCSS) 只是查看源代码中是否包含类,如果包含则保留它们。它不包括动态创建的类,例如bg-${button.color}.

我建议的解决方法是这样的:

const backgroundClassMap = {
    "custom-blue": "bg-custom-blue",
};

...

<button class={`some other classes ${backgroundClassMap[button.color]}`}>

因为通过这个方法,类bg-custom-blue确实存在并正在使用,因此不会将其从构建中排除。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Tailwind 自定义颜色在 Next.js 项目中不起作用[重复] 的相关文章

随机推荐