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

如何为react-data-table动态设置不同行背景色?

为react-data-table-component表格行设置动态背景色

react-data-table-component 提供了 rowStyle 属性,支持传入函数根据每行数据动态生成样式,刚好能实现你要的效果。

实现步骤:

  1. 定义行样式函数,接收当前行的row数据作为参数,根据业务条件(比如职位、ID等)返回对应背景色样式
  2. 将该函数传递给DataTable组件的rowStyle属性

修改后的完整代码:

import {
  Flex,
  useColorModeValue,
  Button,
  ButtonGroup,
  Input,
  VStack,
  HStack,
  Stack,
  Image,
  Text,
} from "@chakra-ui/react";
import React from "react";
import DataTable from 'react-data-table-component';

export default function ColumnsTable(props) {
  // 定义动态行样式函数
  const getRowStyle = (row) => {
    // 去除职位字段前后空格,避免判断出错
    const position = row.position.trim();
    // 根据职位返回对应背景色
    switch(position) {
      case 'Industrial Designer':
        return { backgroundColor: '#f0f7ff' };
      case 'Graphic Designer':
        return { backgroundColor: '#fff3e0' };
      case 'Product Manager':
        return { backgroundColor: '#e8f5e9' };
      default:
        return {}; // 默认无特殊背景
    }
  };

  const columns = [
    {
      name: (<Text fontSize={'15px'}>Id</Text>),
      selector: row =>(<Text fontSize={'15px'}>{row.id}</Text>) ,
      sortable: true,
    },
    {
      name: (<Text fontSize={'15px'}>Name</Text>),
      selector: row =>(<Text fontSize={'15px'}>{row.name}</Text>) ,
      sortable: true,
    },
    {
      name: (<Text fontSize={'15px'}>Current Position</Text>),
      selector: row =>(<Text fontSize={'15px'}>{row.position}</Text>) ,
      sortable: true,
    },
    {
      name: (<Text fontSize={'15px'}>Birthday Date</Text>),
      selector: row =>(<Text fontSize={'15px'}>{row.birthDay}</Text>) ,
      sortable: true,
    },
  ];

  const data = [
    {
      id: 1,
      name: 'Annette Black',
      position: '   Industrial Designer',
      birthDay:'12-06-1998'
    },
    {
      id: 2,
      name: 'Bessie Cooper',
      position: 'Graphic Designer',
      birthDay:'12-06-1998'
    },
    {
      id: 2,
      name: '   Leslie Alexander',
      position: '   Industrial Designer',
      birthDay:'12-06-1998'
    },
    {
      id: 3,
      name: 'Leslie Alexander',
      position: 'Graphic Designer',
      birthDay:'12-06-1998'
    },
    {
      id: 4,
      name: 'Leslie Alexander',
      position: '   Product Manager',
      birthDay:'12-06-1998'
    },
  ]

  return (
    <Stack w={'74vw'} bg='white' mt={5} py={5}>
      <DataTable
        title='Upcoming Birthday'
        columns={columns}
        data={data}
        rowStyle={getRowStyle} // 绑定动态行样式
      />
    </Stack>
  );
}

说明:

  • 你可以根据实际需求调整getRowStyle函数的判断逻辑,比如根据ID、日期或其他字段设置背景色
  • 颜色值可替换为设计稿对应的代码
  • 如果需要hover、active等状态样式,可结合组件的customStyles属性进一步定制

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 09:05:36