You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何通过JavaScript变量为Tailwind元素添加的样式不生效?

问题说明

按钮样式对比

两个按钮的情况:

  • "SHOP NOW":用JavaScript变量bgColor拼接类名bg-[${bgColor}]设置背景色
  • "LATEST COLLECTION":直接写静态Tailwind类名bg-[#FFD6D9]设置背景色

从浏览器检查面板能看到两个按钮的类名都存在,但第一个按钮的背景色就是不生效。

源代码

const Category = () => {
      const bgColor = "#FFE6D9";

  return (
    <div className="flex flex-col gap-12 justify-center items-center mt-12 ">
      <button className={`bg-[${bgColor}]`}>SHOP NOW</button>
      <button className={`bg-[#FFD6D9]`}>LATEST COLLECTION</button>
    </div>
  );
}

export default Category
原因及解决办法

为啥会这样?

Tailwind的JIT(即时编译)模式只会编译代码里静态写死的类名。你用JS变量拼接出来的bg-[${bgColor}],编译工具在打包时没法识别具体的颜色值,就不会生成对应的CSS样式规则,所以类名虽然挂在元素上,但没有生效的样式。

怎么解决?

给你几个可行的方案:

  1. 直接用内联样式
    最简单的方式,直接通过style属性设置背景色:
<button style={{ backgroundColor: bgColor }}>SHOP NOW</button>
  1. 提前枚举所有可能的颜色类
    如果颜色是固定的几个选项,可以提前把所有可能的Tailwind类名写出来,再通过条件判断选择:
const Category = () => {
  const bgColor = "#FFE6D9";

  return (
    <div className="flex flex-col gap-12 justify-center items-center mt-12 ">
      <button className={bgColor === "#FFE6D9" ? "bg-[#FFE6D9]" : "bg-[其他颜色值]"}>SHOP NOW</button>
      <button className="bg-[#FFD6D9]">LATEST COLLECTION</button>
    </div>
  );
}
  1. 在Tailwind配置里自定义颜色
    把常用的颜色注册到tailwind.config.js里,之后直接用对应的类名:
// tailwind.config.js
module.exports = {
  theme: {
    extend: {
      colors: {
        shopOrange: "#FFE6D9",
        collectionPink: "#FFD6D9",
      },
    },
  },
};

然后组件里这么用:

const Category = () => {
  const bgColor = "shopOrange";

  return (
    <div className="flex flex-col gap-12 justify-center items-center mt-12 ">
      <button className={`bg-${bgColor}`}>SHOP NOW</button>
      <button className="bg-collectionPink">LATEST COLLECTION</button>
    </div>
  );
}
  1. 混合使用Tailwind工具类和内联样式
    如果需要保留Tailwind的其他样式(比如 padding、圆角),只动态改背景色:
<button className="px-4 py-2 rounded-md" style={{ backgroundColor: bgColor }}>SHOP NOW</button>

内容的提问来源于stack exchange,提问作者Malhar Soomro

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 06:42:59