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

React.js的Grid Layout中如何为不同网格项设置不同背景色

实现方案

你可以通过动态绑定样式类的方式实现需求,总共两步修改:

第一步:修改CSS文件

在原有Ticket.css的末尾新增三个优先级对应的背景样式:

/* 优先级对应背景色,可根据视觉需要调整色值 */
.card.high {
  background-color: #ff4d4f;
}
.card.medium {
  background-color: #faad14;
}
.card.low {
  background-color: #52c41a;
}

如果需要浅色背景提升可读性,可以将对应色值替换为#fff1f0、#fffbe6、#f6ffed。

第二步:修改Ticket.js文件

调整ContentWrapper组件的className属性,通过模板字符串动态拼接优先级对应的类名即可:
找到渲染列表的map部分,将

<ContentWrapper className="card" >

修改为

<ContentWrapper className={`card ${tickets.priority}`} >

如果担心后端返回的priority值不符合预期,可以增加一层映射判断,代码更稳妥:

{ticket.map((tickets,key) => {
  // 新增优先级映射,避免异常值导致样式失效
  const priorityMap = {
    high: 'high',
    medium: 'medium',
    low: 'low'
  }
  const bgClass = priorityMap[tickets.priority] || ''
  return (
    <ContentWrapper className={`card ${bgClass}`} >
      {/* 原有内部代码保持不变 */}
      <p style={{fontSize:"20px" , fontWeight:"bold", color:"#5c5c5c"}}>{tickets.ticketTitle}</p>
      <hr style={{marginTop:"-18px"}}></hr>
      <p className="contain">{tickets.priority}</p> 
      <button class="button">send</button>
    </ContentWrapper>
  )
})}

可选优化:清理冗余代码

你当前代码中定义的tickets状态、以及包含high/medium/low的state状态都没有实际使用,可以直接删除,减少不必要的代码。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 12:51:02