antd 表格合计栏

用的Antd 的 UI 框架。

场景:table 中后面想添加一行合计。合计的值前端计算得到。目前想到两种方法。

第一种:比较好维护。
第二种:使用antd4中summary

方法一:把合计行插入到数组中

需要对每列求和,然后插入到数组中
在这里插入图片描述

import React, { useEffect, useState } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { Form, Input, Button, Card, Table } from 'antd';
/**
  * 单元格合并处理
  * @param text 当前单元格的值
  * @param data 当前分页所有数据
  * @param key 当前列的dataIndex
  * @param index 当前数据所在下标
  * @returns {number} 待合并单元格数量
  */
const mergeCells = (text, data, key, index) => {
    // 上一行该列数据是否一样
    if (index !== 0 && text === data[index - 1][key]) {
        return 0
    }
    let rowSpan = 1
    // 判断下一行是否相等
    for (let i = index + 1; i < data.length; i++) {
        if (text !== data[i][key]) {
            break
        }
        rowSpan++
    }
    return rowSpan
}

export default () => {
    const list = [
        {
            id: '1',
            group: '组一',
            age: 32,
            age1: 32,
            user: '用户1',
            select: true,
        },
        {
            id: '1',
            group: '组一',
            age: 32,
            age1: 32,
            user: '用户1',
            select: true,
        },
        {
            id: '1',
            group: '组二',
            age: 32,
            age1: 32,
            user: '用户1',
            select: true,
        },
        {
            id: '1',
            group: '组二',
            age: 32,
            age1: 32,
            user: '用户1',
            select: true,
        },
        {
            id: '1',
            group: '组三',
            age: 32,
            age1: 32,
            user: '用户1',
            select: true,
        },
        {
            id: '1',
            group: '组四',
            age: 32,
            age1: 32,
            user: '用户1',
            select: true,
        },
        {
            id: '1',
            group: '组五',
            age: 32,
            age1: 8,
            user: '用户1',
            select: true,
        },
        {
            id: '1',
            group: '组五',
            age: 32,
            age1: 32,
            user: '用户1',
            select: true,
        },
    ];
    //定义获取求和方法
    const getSummaries = (columns, data) => {
        const sums = [];
        let sumsInfo = {};
        columns?.forEach((column, index) => {
            if (index === 0) {
                sums[index] = '总价';
                sumsInfo = { total: '合计' }
                return;
            }
            const values = data?.map(item => item[column.dataIndex]);
            if (!values.every(value => isNaN(value))) {
                let sum = values.reduce((prev, curr) => {
                    const value = Number(curr);
                    if (!isNaN(value)) {
                        return prev + curr;
                    } else {
                        return prev;
                    }
                }, 0);
                sums[index] = sum
                sumsInfo = { ...sumsInfo, [column.dataIndex]: sum }
                sums[index] += ' 元';
            } else {
                sums[index] = 'N/A';
            }
        });
        return { sumsInfo, sums };
    }

    const getTotal = (columns, currentData) => {
        const sums = {
            index: '',
            group: '',
            age: 0,
            age1: 0,
            user: '合计',
        }
        let sumObj = getSummaries(columns, currentData).sumsInfo
        return { ...sums, ...sumObj }
    }
    const columns = [
        {

            title: 'group',
            dataIndex: 'group',
            key: 'group',
            render: (text, record, index) => {
                const obj = {
                    children: text !== null ? text : '',
                    props: {}
                }
                obj.props.rowSpan = mergeCells(text, dataSource, 'group', index)
                return obj
            }
        },
        {
            title: '用户',
            dataIndex: 'user',
            key: 'user',
        },
        {
            title: '年龄',
            dataIndex: 'age',
            key: 'age',
        },
        {
            title: '年龄',
            dataIndex: 'age1',
            key: 'age1',
        },
        {
            title: '住址',
            dataIndex: 'address',
            key: 'address',
        },
    ];
    let sums = getTotal(columns, list)
    const dataSource = list && list.length > 0 ? [...list, sums] : [];

    console.log("getTotal", getTotal(columns, list))


    return (
        <PageContainer>
            <Card title="Default size card">
                <Table dataSource={dataSource} columns={columns} rowKey={record => record.id} bordered
                />
            </Card>
        </PageContainer>
    );
}

方法二、使用antd4中summary

import React, { useEffect, useState } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { Form, Input, Button, Card, Table } from 'antd';
/**
  * 单元格合并处理
  * @param text 当前单元格的值
  * @param data 当前分页所有数据
  * @param key 当前列的dataIndex
  * @param index 当前数据所在下标
  * @returns {number} 待合并单元格数量
  */
const mergeCells = (text, data, key, index) => {
    // 上一行该列数据是否一样
    if (index !== 0 && text === data[index - 1][key]) {
        return 0
    }
    let rowSpan = 1
    // 判断下一行是否相等
    for (let i = index + 1; i < data.length; i++) {
        if (text !== data[i][key]) {
            break
        }
        rowSpan++
    }
    return rowSpan
}

export default () => {
    const dataSource = [
        {
            id: '1',
            group: '组一',
            age: 32,
            user: '用户1',
            select: true,
        },
        {
            id: '1',
            group: '组一',
            age: 32,
            user: '用户1',
            select: true,
        },
        {
            id: '1',
            group: '组二',
            age: 32,
            user: '用户1',
            select: true,
        },
        {
            id: '1',
            group: '组二',
            age: 32,
            user: '用户1',
            select: true,
        },
        {
            id: '1',
            group: '组三',
            age: 32,
            user: '用户1',
            select: true,
        },
        {
            id: '1',
            group: '组四',
            age: 32,
            user: '用户1',
            select: true,
        },
        {
            id: '1',
            group: '组五',
            age: 32,
            user: '用户1',
            select: true,
        },
        {
            id: '1',
            group: '组五',
            age: 32,
            user: '用户1',
            select: true,
        },
    ];
    const columns = [
        {

            title: 'group',
            dataIndex: 'group',
            key: 'group',
            render: (text, record, index) => {
                const obj = {
                    children: text !== null ? text : '',
                    props: {}
                }
                obj.props.rowSpan = mergeCells(text, dataSource, 'group', index)
                return obj
            }
        },
        {
            title: '用户',
            dataIndex: 'user',
            key: 'user',
        },
        {
            title: '年龄',
            dataIndex: 'age',
            key: 'age',
        },
        {
            title: '年龄',
            dataIndex: 'age2',
            key: 'age2',
        },
        {
            title: '住址',
            dataIndex: 'address',
            key: 'address',
        },
    ];
    /**
   * @fun self-define summery.
   * @param currentData
   * @returns {*}
   */
    const onSummary = (currentData) => {
        const a = {
            index: '总计',
            user: "总计",
            age: 0,
            

        };
        console.log(currentData);
        const data = currentData.reduce((total, currentValue, currentIndex, arr) => {
            return {
                ...a,
                age: total.age + currentValue.age,
            }
        }, a)
        return <>
            <Table.Summary.Row>
                {columns
                    .map((i, j) =>
                        <Table.Summary.Cell key={j + 1} index={j + 1}>
                            {data[i.dataIndex]}
                        </Table.Summary.Cell>
                    )
                }
            </Table.Summary.Row>
        </>
    }

    return (
        <PageContainer>
            <Card title="Default size card">
                <Table dataSource={dataSource} columns={columns} rowKey={record => record.id} bordered
                    summary={(currentData) => onSummary(currentData)}
                />
            </Card>
        </PageContainer>
    );
}
  • 5
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
Ant Design的表格组件支持嵌套表格功能。具体可以通过以下步骤实现: 1. 在columns数组中,添加一个子表格的render方法。该方法返回一个新的表格组件,其中columns属性为子表格的列。 2. 在父表格的dataSource数据中,为每一个需要展示子表格的行添加一个children属性。该属性为一个数组,包含子表格中的数据。同时,子表格数据的格式也需要与父表格数据的格式一致。 下面是一个简单的示例代码: ``` import React, { useState } from 'react'; import { Table } from 'antd'; const columns = [ { title: '姓名', dataIndex: 'name', key: 'name' }, { title: '年龄', dataIndex: 'age', key: 'age' }, { title: '地址', dataIndex: 'address', key: 'address' }, { title: '操作', dataIndex: '', key: 'x', render: () => <a>展开</a>, }, ]; const data = [ { key: 1, name: 'John Brown', age: 32, address: 'New York No. 1 Lake Park', children: [ { key: 11, name: 'Jim Green', age: 42, address: 'London No. 1 Lake Park', }, { key: 12, name: 'Joe Black', age: 32, address: 'Sidney No. 1 Lake Park', }, ], }, { key: 2, name: 'Joe Black', age: 32, address: 'Sidney No. 1 Lake Park', }, ]; const NestedTable = () => { const [expandedRowKeys, setExpandedRowKeys] = useState([]); const onExpand = (expanded, record) => { if (expanded) { setExpandedRowKeys([...expandedRowKeys, record.key]); } else { setExpandedRowKeys(expandedRowKeys.filter((key) => key !== record.key)); } }; return ( <Table columns={columns} dataSource={data} expandedRowKeys={expandedRowKeys} onExpand={onExpand} rowKey="key" expandable={{ expandedRowRender: (record) => ( <Table columns={columns} dataSource={record.children} rowKey="key" /> ), }} /> ); }; export default NestedTable; ``` 在这个示例中,我们创建了一个包含两行数据的父表格。第一行数据包含一个子表格,我们使用了children属性为其指定子表格数据。同时,在columns数组中添加了一个render方法,用于展示子表格。在父表格组件中,我们使用了antd的expandable属性,指定了展开子表格的方式和渲染方法。 希望这个示例能够帮助你了解如何在Ant Design的表格组件中实现嵌套表格功能。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值