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

求助:在material-react-table中实现薪资表指定列的求和计算

解决material-react-table薪资表计算逻辑问题的方案

1. 配置行内计算列

直接在你的columns数组里新增收入总计、扣除总计、实发工资(Net Payment)这三个计算列,用accessorFn实现每行的实时计算:

const columns = [
  // 保留原有列:Id、First Name、Basic Wage、HRA、PF、ESIC等
  {
    accessorKey: 'earningsTotal',
    header: '收入总计',
    accessorFn: (row) => row.basicWage + row.hra + row.otherAllowance, // 把所有薪资项按实际字段加进去
    aggregationFn: 'sum', // 开启总计行求和
  },
  {
    accessorKey: 'deductionsTotal',
    header: '扣除总计',
    accessorFn: (row) => row.pf + row.esic + row.otherDeduction, // 把所有扣除项按实际字段加进去
    aggregationFn: 'sum',
  },
  {
    accessorKey: 'netPayment',
    header: '实发工资',
    accessorFn: (row) => {
      const totalEarnings = row.basicWage + row.hra + row.otherAllowance;
      const totalDeductions = row.pf + row.esic + row.otherDeduction;
      return totalEarnings - totalDeductions;
    },
    // 自定义聚合逻辑,避免每行实发求和的精度误差,直接用收入总计减扣除总计
    aggregationFn: (rows) => {
      const totalEarnings = rows.reduce((sum, row) => sum + (row.basicWage + row.hra + row.otherAllowance), 0);
      const totalDeductions = rows.reduce((sum, row) => sum + (row.pf + row.esic + row.otherDeduction), 0);
      return totalEarnings - totalDeductions;
    },
  },
  // 如果原有Grand Total就是收入总计,可直接替换成上面的earningsTotal列,或保留调整
];

2. 开启表格聚合功能

确保你的MaterialReactTable组件开启总计行功能:

<MaterialReactTable
  columns={columns}
  data={yourEmployeeSalaryData}
  enableAggregation
  initialState={{ showAggregationRow: true }} // 默认显示底部总计行
  enableBottomToolbar={true}
/>

3. 后端数据预计算(可选)

如果数据从后端获取,也可以在查询时提前计算好每行的汇总字段,减轻前端计算压力:

// 假设你的数据查询函数
const fetchSalaryData = async () => {
  const res = await fetch('/api/employee-salaries');
  const rawData = await res.json();
  return rawData.map(row => ({
    ...row,
    earningsTotal: row.basicWage + row.hra + row.otherAllowance,
    deductionsTotal: row.pf + row.esic + row.otherDeduction,
    netPayment: (row.basicWage + row.hra + row.otherAllowance) - (row.pf + row.esic + row.otherDeduction),
  }));
};

注意点

  • 如果薪资/扣除项是动态增减的,可把这类字段存为数组(比如earnings: [{name: 'Basic Wage', amount: 5000}, ...]),再用row.earnings.reduce((sum, item) => sum + item.amount, 0)计算,扩展性更强
  • 金额计算注意浮点精度问题,建议用Number.toFixed(2)格式化,或用decimal.js这类库处理

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 02:42:31