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