123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121 |
- import React, { PureComponent, Fragment } from 'react';
- import { Table, Alert } from 'antd';
- import styles from './index.less';
-
- function initTotalList(columns) {
- const totalList = [];
- columns.forEach(column => {
- if (column.needTotal) {
- totalList.push({ ...column, total: 0 });
- }
- });
- return totalList;
- }
-
- class StandardTable extends PureComponent {
- constructor(props) {
- super(props);
- const { columns } = props;
- const needTotalList = initTotalList(columns);
-
- this.state = {
- selectedRowKeys: [],
- needTotalList,
- };
- }
-
- componentWillReceiveProps(nextProps) {
- // clean state
- if (nextProps.selectedRows.length === 0) {
- const needTotalList = initTotalList(nextProps.columns);
- this.setState({
- selectedRowKeys: [],
- needTotalList,
- });
- }
- }
-
- handleRowSelectChange = (selectedRowKeys, selectedRows) => {
- let needTotalList = [...this.state.needTotalList];
- needTotalList = needTotalList.map(item => {
- return {
- ...item,
- total: selectedRows.reduce((sum, val) => {
- return sum + parseFloat(val[item.dataIndex], 10);
- }, 0),
- };
- });
-
- if (this.props.onSelectRow) {
- this.props.onSelectRow(selectedRows);
- }
-
- this.setState({ selectedRowKeys, needTotalList });
- };
-
- handleTableChange = (pagination, filters, sorter) => {
- this.props.onChange(pagination, filters, sorter);
- };
-
- cleanSelectedKeys = () => {
- this.handleRowSelectChange([], []);
- };
-
- render() {
- const { selectedRowKeys, needTotalList } = this.state;
- const { data: { list, pagination }, loading, columns, rowKey } = this.props;
-
- const paginationProps = {
- showSizeChanger: true,
- showQuickJumper: true,
- ...pagination,
- };
-
- const rowSelection = {
- selectedRowKeys,
- onChange: this.handleRowSelectChange,
- getCheckboxProps: record => ({
- disabled: record.disabled,
- }),
- };
-
- return (
- <div className={styles.standardTable}>
- <div className={styles.tableAlert}>
- <Alert
- message={
- <Fragment>
- 已选择 <a style={{ fontWeight: 600 }}>{selectedRowKeys.length}</a> 项
- {needTotalList.map(item => (
- <span style={{ marginLeft: 8 }} key={item.dataIndex}>
- {item.title}总计
- <span style={{ fontWeight: 600 }}>
- {item.render ? item.render(item.total) : item.total}
- </span>
- </span>
- ))}
- <a onClick={this.cleanSelectedKeys} style={{ marginLeft: 24 }}>
- 清空
- </a>
- </Fragment>
- }
- type="info"
- showIcon
- />
- </div>
- <Table
- loading={loading}
- rowKey={rowKey || 'key'}
- rowSelection={rowSelection}
- dataSource={list}
- columns={columns}
- pagination={paginationProps}
- onChange={this.handleTableChange}
- />
- </div>
- );
- }
- }
-
- export default StandardTable;
|