React中如何根据条件设置DataTable指定单元格背景色?
解决方案
要实现你需要的单元格背景色设置,需要调整数据渲染逻辑,并针对目标列和单元格添加条件样式。以下是修改后的完整代码及关键说明:
修改后的代码
import { useState } from "react"; export default function DataTable1(){ const rawData= [[7,'',2,1,4,3],[8,3,'',5,3],['','','',''],[4,4,'']] return ( <table> <thead> <tr> <th></th> <th>Week 1</th> <th>Week 2</th> <th>Week 3</th> <th>Week 4</th> <th>Net Lost</th> <th>Net Recovered</th> </tr> </thead> <tbody> {rawData.map((item, rowIndex) => { // 定位当前行第一个有值的单元格索引 const firstNonEmptyIndex = item.findIndex(itm => itm !== ''); return ( <tr key={rowIndex}> <th>Week {rowIndex + 1}</th> {/* 先渲染行内已有数据 */} {item.map((itm, colIndex) => { let cellStyle = {}; // 仅处理Week 1-4列(排除最后两列) if (colIndex < 4) { if (itm !== '') { // 第一个有值单元格设红色,其余设绿色 cellStyle.backgroundColor = colIndex === firstNonEmptyIndex ? 'red' : 'green'; cellStyle.color = 'white'; // 可选:优化文字可读性 } } return <td key={colIndex} style={cellStyle}>{itm}</td>; })} {/* 补充空缺的单元格(保证列数与表头一致) */} {[...Array(6 - item.length)].map((_, emptyIdx) => ( <td key={`empty-${emptyIdx}`}></td> ))} </tr> ); })} </tbody> </table> ); }
关键修改点
修正列对应逻辑:
原代码先补空单元格再渲染数据,会导致列与表头错位。调整为先渲染item内的数据,再补充空单元格,确保Week 1-4、Net Lost、Net Recovered列一一对应。条件样式判断:
- 对每行计算
firstNonEmptyIndex,标记该行第一个非空单元格的位置 - 仅对前4列(Week 1-4)设置背景色,自动排除最后两列(Net Lost/Net Recovered)
- 有值单元格中,第一个非空单元格用红色背景,其余非空单元格用绿色背景
- 对每行计算
优化细节:
- 添加
key属性避免React渲染警告 - 可选设置文字为白色,提升深色背景下的可读性
- 添加
替代方案:使用CSS类(推荐)
如果希望样式与逻辑分离,可以定义CSS类:
.cell-red { background-color: red; color: white; } .cell-green { background-color: green; color: white; }
然后将代码中的cellStyle替换为className判断:
let cellClass = ''; if (colIndex < 4 && itm !== '') { cellClass = colIndex === firstNonEmptyIndex ? 'cell-red' : 'cell-green'; } return <td key={colIndex} className={cellClass}>{itm}</td>;
内容的提问来源于stack exchange,提问作者Deric
相关产品推荐
相关产品推荐

