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

如何在React中基于数组生成带统计的薪资表格?

实现步骤

1. 数据预处理

首先需要将原始的货币-行业数组转换为React Table可用的结构化数据,同时计算各行业的货币数量统计及总计行。

const processData = (rawData) => {
  const sectorMap = new Map();
  const allCurrencies = new Set();

  // 遍历原始数据,统计每个行业下的货币数量
  rawData.forEach(([currency, sector]) => {
    allCurrencies.add(currency);
    if (!sectorMap.has(sector)) {
      sectorMap.set(sector, {});
    }
    const sectorData = sectorMap.get(sector);
    sectorData[currency] = (sectorData[currency] || 0) + 1;
  });

  // 转换为表格行数据,补充缺失货币的0值并计算行业总计
  const processedData = Array.from(sectorMap.entries()).map(([sector, counts]) => {
    const total = Object.values(counts).reduce((sum, count) => sum + count, 0);
    const fullCounts = {};
    allCurrencies.forEach(curr => {
      fullCounts[curr] = counts[curr] || 0;
    });
    return { sector, ...fullCounts, total };
  });

  // 计算全局总计行
  const overallTotals = { sector: 'Total' };
  let grandTotal = 0;
  allCurrencies.forEach(curr => {
    const sum = processedData.reduce((sum, row) => sum + row[curr], 0);
    overallTotals[curr] = sum;
    grandTotal += sum;
  });
  overallTotals.total = grandTotal;

  return { processedData, overallTotals, currencies: Array.from(allCurrencies) };
};

2. React Table组件实现

使用react-table库构建表格,动态生成列配置,并添加总计行:

import React from 'react';
import { useTable } from 'react-table';
import './TableStyles.css';

const CurrencySectorTable = () => {
  // 原始数据
  const rawData = [
    ['Euro','Tech'],
    ['USD','Tech'],
    ['GBX', 'Health'],
    ['Euro', 'Real Estate'], 
    ['GBX', 'Real Estate']
  ];

  // 处理数据
  const { processedData, overallTotals, currencies } = processData(rawData);

  // 动态生成列配置
  const columns = [
    {
      Header: 'Sector',
      accessor: 'sector',
      style: { textAlign: 'left' }
    },
    ...currencies.map(curr => ({
      Header: curr,
      accessor: curr,
      style: curr === 'Euro' ? { textAlign: 'center' } : { textAlign: 'right' }
    })),
    {
      Header: 'Total',
      accessor: 'total',
      style: { textAlign: 'right' }
    }
  ];

  // 初始化React Table
  const {
    getTableProps,
    getTableBodyProps,
    headerGroups,
    rows,
    prepareRow
  } = useTable({ columns, data: processedData });

  return (
    <div className="s-table-container">
      <table className="s-table" {...getTableProps()}>
        <thead>
          {headerGroups.map(headerGroup => (
            <tr {...headerGroup.getHeaderGroupProps()}>
              {headerGroup.headers.map(column => (
                <th {...column.getHeaderProps()} style={column.style}>
                  {column.render('Header')}
                </th>
              ))}
            </tr>
          ))}
        </thead>
        <tbody {...getTableBodyProps()}>
          {/* 渲染行业数据行 */}
          {rows.map(row => {
            prepareRow(row);
            return (
              <tr {...row.getRowProps()}>
                {row.cells.map(cell => (
                  <td {...cell.getCellProps()} style={cell.column.style}>
                    {cell.render('Cell')}
                  </td>
                ))}
              </tr>
            );
          })}
          {/* 渲染总计行 */}
          <tr>
            <td style={{ textAlign: 'left' }}>{overallTotals.sector}</td>
            {currencies.map(curr => (
              <td key={curr} style={curr === 'Euro' ? { textAlign: 'center' } : { textAlign: 'right' }}>
                {overallTotals[curr]}
              </td>
            ))}
            <td style={{ textAlign: 'right' }}>{overallTotals.total}</td>
          </tr>
        </tbody>
      </table>
    </div>
  );
};

export default CurrencySectorTable;

3. 样式文件(TableStyles.css)

添加表格样式以匹配目标格式:

.s-table-container {
  margin: 20px;
}

.s-table {
  width: 100%;
  border-collapse: collapse;
  border: 1px solid #e0e0e0;
}

.s-table th, .s-table td {
  border: 1px solid #e0e0e0;
  padding: 12px 15px;
}

.s-table th {
  background-color: #f5f5f5;
  font-weight: 600;
}

.s-table tbody tr:nth-child(even) {
  background-color: #fafafa;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 17:55:42