import { Alert, Table } from 'antd'; import { PaginationConfig, SorterResult, TableCurrentDataSource } from 'antd/lib/table'; import React, { Component, Fragment } from 'react'; import styles from './index.less'; function initTotalList(columns) { const totalList = []; columns.forEach(column => { if (column.needTotal) { totalList.push({ ...column, total: 0 }); } }); return totalList; } interface StandardTableProps { columns: any; onSelectRow: (row: any) => void; data: any; rowKey?: string; selectedRows: any[]; onChange?: ( pagination: PaginationConfig, filters: Record, sorter: SorterResult, extra?: TableCurrentDataSource, ) => void; loading?: boolean; } interface StandardTableState { selectedRowKeys: any[]; needTotalList: any[]; } class StandardTable extends Component { static getDerivedStateFromProps(nextProps) { // clean state if (nextProps.selectedRows.length === 0) { const needTotalList = initTotalList(nextProps.columns); return { selectedRowKeys: [], needTotalList, }; } return null; } constructor(props) { super(props); const { columns } = props; const needTotalList = initTotalList(columns); this.state = { selectedRowKeys: [], needTotalList, }; } handleRowSelectChange = (selectedRowKeys, selectedRows) => { let { needTotalList } = this.state; needTotalList = needTotalList.map(item => ({ ...item, total: selectedRows.reduce((sum, val) => sum + parseFloat(val[item.dataIndex]), 0), })); const { onSelectRow } = this.props; if (onSelectRow) { onSelectRow(selectedRows); } this.setState({ selectedRowKeys, needTotalList }); }; handleTableChange = (pagination, filters, sorter) => { const { onChange } = this.props; if (onChange) { onChange(pagination, filters, sorter); } }; cleanSelectedKeys = () => { this.handleRowSelectChange([], []); }; render() { const { selectedRowKeys, needTotalList } = this.state; const { data = {}, rowKey, ...rest } = this.props; const { list = [], pagination } = data; const paginationProps = { showSizeChanger: true, showQuickJumper: true, ...pagination, }; const rowSelection = { selectedRowKeys, onChange: this.handleRowSelectChange, getCheckboxProps: record => ({ disabled: record.disabled, }), }; return (
已选择 {selectedRowKeys.length} 项   {needTotalList.map(item => ( {item.title} 总计  {item.render ? item.render(item.total) : item.total} ))} 清空 } type="info" showIcon />
); } } export default StandardTable;