table列表自定义合计(react antd)

117 阅读1分钟
interface TableItem {
  [key: string]: number;
} 

function getTotalByKeys(tableList: TableItem[], keys: string[]): TableItem {
  const total: TableItem = {};
  for (const item of tableList) {
    for (const key of keys) {
      total[key] =
        (total[key] || 0) + (typeof item[key] === "number" ? item[key] : 0);
    }
  }
  return total;
} 
// 进行合并计算操作
const useTableTotal = (
  // 合计
  value: any[],
  totalName: string,
  requiredTotalName: string[],
  callback?: (arg0: any[], arg1: string[]) => any
): any => {
  if (value.length === 0) {
    return value;
  }

  let resultTotalByValue: any;
  if (callback) {
    return callback(value, requiredTotalName);
  } else {
    resultTotalByValue = getTotalByKeys(value, requiredTotalName);
    value.push({
      [totalName]: "合计",
      ...resultTotalByValue,
    });
    return value;
  }
};

export default useTableTotal;
interface TableItem {
  [key: string]: number;
}

function getTotalByKeys(tableList: TableItem[], keys: string[]): TableItem {
  const total: TableItem = {};
  for (const item of tableList) {
    for (const key of keys) {
      total[key] =
        (total[key] || 0) + (typeof item[key] === "number" ? item[key] : 0);
    }
  }
  return total;
}

const useTableTotal = (
  // 合计
  value: any[],
  totalName: string,
  requiredTotalName: string[],
  callback?: (arg0: any[], arg1: string[]) => any
): any => {
  if (value.length === 0) {
    return value;
  }

  let resultTotalByValue: any;
  if (callback) {
    return callback(value, requiredTotalName);
  } else {
    resultTotalByValue = getTotalByKeys(value, requiredTotalName);
    value.push({
      [totalName]: "合计",
      ...resultTotalByValue,
    });
    return value;
  }
};

export default useTableTotal;

//useTableTotal(data, 'ctCode', ['onlineNonInvoicing', 'offlineInvoicing', 'offlineNonInvoicing', 'financeRecharge', 'total'])
//第一个参数后端返回的list 第二个参数合计渲染的字段名称,第三个参数string[]类型需要合计的字段名,第四个参数callback你可以自行返回any[](返回的东西就是返回值)