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

React中动态修改文本颜色的问题求助

解决JSX中动态设置文本颜色的问题

你的代码存在语法错误导致动态颜色无法生效,这里提供两种可行的解决方式:

1. 修复Tailwind className语法错误

原代码里的className模板字符串多了一个多余的双引号,导致样式解析失败,修正后即可正常生效:

const steps = [
  {
    title: 'Step 1',
    color: '#7C3EDA',
    name: 'Medical History',
    source: '/assets/Star2.png',
    desc: "Complete a simple medical history form so your provider can develop the best treatment plan for you. It's fast, easy, and free."
  },
  {
    title: 'Step 2',
    color: '#17CBBE',
    name: 'Online Visit',
    source: '/assets/Star3.png',
    desc: 'Speak to your new healthcare provider licensed to treat your condition with a simple online audio-visual appointment conversation.'
  },
  {
    title: 'Step 3',
    color: '#FF3755',
    name: 'Receive Medications',
    source: '/assets/Star4.png',
    desc: 'If medically appropriate, receive your medication every 30/60/90 days. All GLP-1 Plans come with free shipping directly to your door! Follow up with your provider any time you need assistance.'
  }
]

<div className="py-5 md:py-7 lg:py-20 flex flex-wrap gap-8 justify-center">
  {steps && steps.map((step, index) => (
  <div key={index} className="relative">
    <div className="w-[315px] md:w-[330px] lg:w-[350px] 2xl:w-[380px]">
      <img src={step.source} className="w-full" alt="star" />
    </div>
    <div
      className="absolute top-0 w-[315px] md:w-[330px] lg:w-[350px] 2xl:w-[380px] h-full space-y-2 px-6 py-5 text-center"
    >
      {/* 移除多余双引号,动态颜色生效 */}
      <p className={`font-bold text-[${step.color}] text-4xl`}>
        {step.title}
      </p>
      {/* 若需要给name也设置动态颜色,同样使用text-[${step.color}] */}
      <p className={`font-medium text-2xl text-[${step.color}]`}>{step.name}</p>
      <p className="text-[#666666] text-sm md:text-base">{step.desc}</p>
    </div>
  </div>
  ))}
</div>

2. 使用inline style属性(通用方案)

如果不想依赖Tailwind的动态颜色语法,也可以直接用JSX原生的style属性,这种方式适用于所有React项目:

<p className="font-bold text-4xl" style={{ color: step.color }}>
  {step.title}
</p>

额外提示

  • 用text-[${color}]时,确保你的Tailwind配置支持动态十六进制颜色值,你的场景完全符合要求。
  • 遍历数组时,尽量避免用index作为key,如果数组元素有唯一标识(比如id),用唯一标识作为key会让组件渲染更稳定。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 22:22:40