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

React中如何为className属性赋值变量?代码赋值失败求助

问题解决

问题出在两个核心点:

  • className语法错误:style用双大括号是因为它需要接收对象类型的样式配置,但className只需要直接传入字符串。你写的className={{classNameDiv}}相当于传了一个{ classNameDiv: "colorBox" }的对象,不是字符串,所以样式完全不生效。
  • const变量无法重新赋值:用const声明的classNameDiv是只读的,后面尝试修改它的值会直接报错,必须改成let才能重新赋值。

修正后的代码:

return (
  <div className="item" key={i}>
    <img src={`./images/${myjson.images[index].name}`} alt="" />
    <div className="allBoxes">
      {myjson.images[index].palette.map((index2, j) => {
        const b = myjson.images[index].palette[j]
        let classNameDiv = "colorBox"; // 把const替换为let
        if (RefArrayPalette[index][j] === 1) {
          classNameDiv = "colorBox2";
        }
        return (
          <div
            key={j}
            className={classNameDiv} // 直接传变量,去掉外层多余的大括号
            style={{ backgroundColor: index2 }}
            onClick={calculateNewList}
          />
        )
      }, (i, index))}

更简洁的写法(推荐):

可以用三元表达式直接在className里完成判断,省去单独的变量声明:

return (
  <div className="item" key={i}>
    <img src={`./images/${myjson.images[index].name}`} alt="" />
    <div className="allBoxes">
      {myjson.images[index].palette.map((index2, j) => {
        const b = myjson.images[index].palette[j]
        return (
          <div
            key={j}
            className={RefArrayPalette[index][j] === 1 ? "colorBox2" : "colorBox"}
            style={{ backgroundColor: index2 }}
            onClick={calculateNewList}
          />
        )
      }, (i, index))}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 09:24:27