可以通过遍历每一行并计算相似行的列值总和来解决此问题。具体步骤如下:
- 用Ant Design Table展示数据。
import React, { useState } from "react";
import { Table } from "antd";
const dataSource = [
{ key: "1", name: "John", age: 32, address: "New York" },
{ key: "2", name: "Mike", age: 28, address: "London" },
{ key: "3", name: "Mary", age: 25, address: "Tokyo" },
{ key: "4", name: "Sarah", age: 36, address: "Paris" },
{ key: "5", name: "Bob", age: 21, address: "Singapore" }
];
const columns = [
{ title: "Name", dataIndex: "name", key: "name" },
{ title: "Age", dataIndex: "age", key: "age" },
{ title: "Address", dataIndex: "address", key: "address" }
];
const ExampleTable = () => {
return (
);
};
export default ExampleTable;
- 添加一个按钮来计算列值总和。
import React, { useState } from "react";
import { Table, Button } from "antd";
const dataSource = [
{ key: "1", name: "John", age: 32, address: "New York" },
{ key: "2", name: "Mike", age: 28, address: "London" },
{ key: "3", name: "Mary", age: 25, address: "Tokyo" },
{ key: "4", name: "Sarah", age: 36, address: "Paris" },
{ key: "5", name: "Bob", age: 21, address: "Singapore" }
];
const columns = [
{ title: "Name", dataIndex: "name", key: "name" },
{ title: "Age", dataIndex: "age", key: "age" },
{ title: "Address", dataIndex: "address", key: "address" }
];
const ExampleTable = () => {
const [data, setData] = useState(dataSource);
const [totalAge, setTotalAge] = useState(0);
const calculateAgeTotal = () => {
let ageTotal = 0;
Object.values(data.reduce((acc, cur) => {
// 如果两行的address字段相同,则把它们加起来
const {name, address, age} = cur;
const key = JSON.stringify([name, address]);
if (acc[key]) {
acc[key].age += age;
} else {
acc[key] = {...cur};
}
return acc;
}, {})).forEach((row) => {
ageTotal += row.age;
})
setTotalAge(ageTotal);
}
return (
<>
年龄总和:{totalAge}
>
);
};
export default ExampleTable;
- 遍历每一行来计算相似行的列值总和。
const calculateAgeTotal = () => {
let