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

React JS中如何为表格添加Net Lost与Net Returned列求和行

解决React数据表添加求和行的问题

要实现表格底部添加Net Lost和Net Returned列的求和行,你需要先计算对应列的总和,再在表格末尾添加格式匹配的总计行,以下是具体方案:

1. 计算求和值

遍历原始数据,把每行里Net Lost(对应数组第5个元素,索引4)和Net Returned(数组第6个元素,索引5)的有效数值累加,空字符串按0处理,同时跳过全空的无效行:

const calculateTotals = () => {
  let netLostTotal = 0;
  let netReturnedTotal = 0;
  
  rawData.forEach(row => {
    // 跳过全空行
    if (row.some(item => item !== '')) {
      const netLost = row[4] !== '' ? Number(row[4]) : 0;
      const netReturned = row[5] !== '' ? Number(row[5]) : 0;
      
      netLostTotal += netLost;
      netReturnedTotal += netReturned;
    }
  });
  
  return { netLostTotal, netReturnedTotal };
};

2. 添加总计行

在tbody的循环渲染结束后,直接添加总计行,保证单元格数量和表头完全匹配:

修改后的完整代码

import { useState } from "react";
import "./style.css";

export default function DataTable4() {
  const rawData = [
    [7, '', 2, 1, 4, 3],
    [8, 3, '', 5, 3],
    ['', '', '', ''],
    [4, 4, '']
  ];

  // 计算求和值
  const calculateTotals = () => {
    let netLostTotal = 0;
    let netReturnedTotal = 0;
    
    rawData.forEach(row => {
      if (row.some(item => item !== '')) {
        const netLost = row[4] !== '' ? Number(row[4]) : 0;
        const netReturned = row[5] !== '' ? Number(row[5]) : 0;
        
        netLostTotal += netLost;
        netReturnedTotal += netReturned;
      }
    });
    
    return { netLostTotal, netReturnedTotal };
  };

  const { netLostTotal, netReturnedTotal } = calculateTotals();
  
  return (
    <table>
      <thead>
        <tr>
          <th>Week</th>
          <th>1</th>
          <th>2</th>
          <th>3</th>
          <th>4</th>
          <th>Net Lost</th>
          <th>Net Returned</th>
        </tr>
      </thead>
      <tbody>
        {rawData.map((item, index) => {
          return (
            <tr key={index}>
              <th>{index + 1}</th>
              {[...Array(6 - item.length)].map((_, idx) => (
                <td key={idx}></td>
              ))}
              {item.map((itm, idx) => (
                <td key={idx}>{itm}</td>
              ))}
            </tr>
          );
        })}
        {/* 新增的总计行 */}
        <tr>
          <th>Total</th>
          <td></td>
          <td></td>
          <td></td>
          <td></td>
          <td>{netLostTotal}</td>
          <td>{netReturnedTotal}</td>
        </tr>
      </tbody>
    </table>
  );
}

补充说明

  • 之前添加<tr>出错大概率是因为单元格数量和表头不匹配,或者未处理空值的求和逻辑
  • 给循环生成的元素加上key属性,避免React列表渲染警告
  • 求和时跳过了全空行,你可以根据实际需求调整这个过滤规则

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 16:05:24