我想在每个文档启动时使用 ReactJS 和 TailwindCSS 在运行时渲染一个具有随机颜色的元素。然而,即使通过检查器查看元素并正确查看类,它仍然不起作用。这是代码:
const colors = ["red", "orange", "amber", "yellow", "lime", "green", "emerald", "teal", "cyan", "light-blue", "blue", "indigo", "violet", "purple", "fuchsia", "pink", "rose"];
const [theme, setTheme] = useState("orange");
useEffect(() => {
setTheme(colors[Math.floor(Math.random() * colors.length)]);
}, []);
return (
<span className={`text-${theme}-400`}>test</span>
);
在 Tailwind 中你不能使用像 bg-${color} 这样的动态类命名。
这是因为当 Tailwind 编译其 CSS 时,它会查找所有代码并检查类名是否匹配。
如果你想要动态名称类,你应该写下所有的类名。 它期望你写这样的东西:
<span className={`${true ? 'text-red-400' : 'text-blue-400'}`}>test</span>
我知道这会使代码更长更冗长,但这是 vanilla tailwindcss 中的唯一方法,您可以使用一些外部包,例如 clsx 或 xwind。
是否建议顺风使用动态类?
答:没有
通常不建议在 tailwind-css 中使用动态类,因为 tailwind 使用 tree-shaking,这意味着源文件中未指定的任何类都不会在输出文件中创建。因此建议使用完整的类名
根据文档
如果您使用字符串插值或将部分类名连接在一起,Tailwind 将找不到它们,因此不会生成相应的 CSS
有解决办法吗?
Ans:是的,在 tailwind.config.cs 中使用 Safelisting 类
安全列表是最后的手段,仅应在无法扫描某些内容的类名的情况下使用。这些情况很少见,您几乎不需要此功能。
特别是对于您来说,您想要具有不同颜色的文本。您可以使用正则表达式来包含您想要使用图案的所有颜色,并相应地指定色调。
注意:您也可以强制 Tailwind 创建变体:
在
tailwind.config.js
module.exports = {
content: [
'./pages/**/*.{html,js}',
'./components/**/*.{html,js}',
],
safelist: [
{
pattern: /text-(red|green|blue|orange)-(100|500|700)/, // You can display all the colors that you need
},
],
// ...
}
要包含所有背景颜色,您可以使用以下代码:
module.exports = {
content: [
...
],
safelist: [
{
pattern: /text-+/, // 👈 This includes bg of all colors and shades
},
],
...
}
您可以尝试获取 CSS 变量来更改调色板,而无需更改 tailwind.config.js
配置文件:
module.exports = {
theme: {
extend: {
colors: {
"primary": {
100:"var(--primary-color-100)",
200:"var(--primary-color-200)",
},
"accent": "var(--accent-color)"
},
},
},
};
css文件:
:root {
--primary-color-100: #fff;
--primary-color-200: #fff00;
--accent-color: #000;
}