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

React中useState仅对部分值生效的问题求助

React中useState仅对部分值生效的问题求助

大家好,我遇到了一个奇怪的问题,想请教下各位开发者朋友。

我在React项目里用useState管理网站的主题色,初始值设为#8D9093:

const [colorTheme, setColorTheme] = useState("#8D9093");

然后写了一个getColorTheme函数,从本地JSON数据里根据网站名称匹配对应的主题色:

const getColorTheme = (websiteName) => {
  const website = websiteData.find(
    (site) => site.name.toLowerCase() === websiteName.toLowerCase()
  );

  if (website) {
    console.log(website.colorTheme);
    setColorTheme(website.colorTheme);
  } else {
    console.log("Website not found");
    setColorTheme("#8D9093");
  }
};

我的JSON数据示例是这样的:

{
  "name": "YouTube",
  "url": "https://www.youtube.com/results?search_query=",
  "colorTheme": "#FF0000"
}

之后我在Tailwind里通过字符串模板使用这个colorTheme:

className={`h-fit w-fit px-2 rounded-xl bg-[${colorTheme}] shadow-[0_0_5px_${colorTheme},0_0_15px_${colorTheme}] text-white`}

现在的问题很诡异:只有YouTube的主题色(#FF0000)能正常在页面上显示变化,其他网站的主题色明明在控制台里能看到被正确设置了,但页面元素的背景和阴影就是没变化。比如控制台打印出了某网站的colorTheme是#1DA1F2,但页面上还是没有应用这个颜色,只有YouTube的能正常生效。

有没有朋友能帮我分析下这是哪里出问题了?

备注:内容来源于stack exchange,提问作者apr2k2

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.21 13:38:12