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

如何在React中仅高亮Material Table的第一行

解决Material Table仅高亮第一行的问题

你当前的rowStyle逻辑错误在于,rowData是单条数据对象而非行索引,rowData[0]会取每条数据的第一个属性值,导致所有行都触发高亮。要实现仅高亮第一行,需要利用rowStyle的第二个参数行索引来判断:

修改rowStyle部分的代码:

rowStyle: (rowData, rowIndex) => ({
    backgroundColor: rowIndex === 0 ? 'blue' : 'transparent', // 可替换为表格默认背景色
})

完整的组件代码调整后如下:

<MaterialTable 
    options={{
        exportButton: true,
        exportAllData: true,
        pageSize: 5,
        pageSizeOptions: [5, 10, 15],
        paging: true,
        actionsColumnIndex: -1,
        rowStyle: (rowData, rowIndex) => ({
            backgroundColor: rowIndex === 0 ? 'blue' : 'transparent',
        })
    }}
    columns={[
        { align:'center',title: 'A', field: 'a'},
        { align:'center',title: 'B', field: 'b'},
        { align:'center',title: 'C', field: 'c'},
        { align:'center',title: 'D', field: 'd'},
    ]}
    tableLayout='fixed'
    data={tableData}
/>

说明:

  • rowStyle函数接收两个参数:rowData(当前行的数据)和rowIndex(当前行的索引,从0开始计数)
  • 通过rowIndex === 0的判断,仅给第一行设置高亮背景色,其他行使用默认背景(示例中用transparent,可根据实际需求替换为表格原本的背景色)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 14:25:19