ant design 中实现表格头部可删除和添加

我是用antd pro做一个项目。有一个小需求是表格头部栏可操作。具体是表头的每一项都带一个“x”按钮,当不想展示这一栏的时候,直接点“x”,这一栏就不展示了。不展示的头部标签放一边,也可以随时加入到表格中。

先看图:

1.表头信息有个“x”,当点击了某一项,该项在表格中消失,并且该标签会在可添加表头上展示。

ant design 中实现表格头部可删除和添加

 

2.此时我“x”掉了序号,用户名两项,得到下面的效果。

ant design 中实现表格头部可删除和添加

 

3.此时我点击了 “+用户名” 标签,表格中再次展示了用户名,同时,可添加表头栏少了 “+用户名” 标签。

ant design 中实现表格头部可删除和添加

 

这项功能在ant design 上的表格组件是没有的,所以我自己在现有组件的基础上实现的。如果你想看懂下面的代码,你需要了解ant design 的表格组件的使用。

import React from 'react';
import { connect } from 'dva';
import GridContent from '@/components/PageHeaderWrapper/GridContent';
import {
  Table,
  Card,
  Form,
  Input,
  Button,
  Tag,
  Select,
  Row,
  Col,
  DatePicker,
  message,
  Tooltip,
  Icon,
} from 'antd';
import { ABNORMAL_AUDIT_STATUS, ABNORMAL_AUDIT_STATUS_COLOR } from '@/constants';
import moment from 'moment';

const { Option } = Select;
const { RangePicker } = DatePicker;

const FormItem = Form.Item;
const risk = ['无', '低', '中', '高', '严重'];
@connect(({ riskEvent, abnormalList, loading }) => ({
  riskEvent,
  abnormalList,
  loading: loading.models.abnormalList,
}))
@Form.create()
class AbnormalList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      selectedData: [],
      newCol: [],
      colKey: {
        id: 0,
        username: 1,
        riskLevel: 2,
        riskScene: 3,
        department: 4,
        createTime: 5,
        status: 6,
        baseInfo: 7,
        operatePlatform: 8,
      },
      columns: [
        {
          title: (
            <div>
              <a onClick={() => this.columsControl('id')}>
                <Icon style={{ fontSize: '6px' }} type="close" />
              </a>{' '}
              序号
            </div>
          ),
          dataIndex: 'id',
          key: '序号',
        },
        {
          title: (
            <div>
              <a onClick={() => this.columsControl('username')}>
                <Icon style={{ fontSize: '6px' }} type="close" />
              </a>{' '}
              用户名
            </div>
          ),
          dataIndex: 'username',
          key: '用户名',
        },
        {
          title: (
            <div>
              <a onClick={() => this.columsControl('riskLevel')}>
                <Icon style={{ fontSize: '6px' }} type="close" />
              </a>{' '}
              风险等级
            </div>
          ),
          dataIndex: 'riskLevel',
          key: '风险等级',
          sorter: true,
          sortDirections: ['descend'],
          render: text => risk[text],
        },
        {
          title: (
            <div>
              <a onClick={() => this.columsControl('riskScene')}>
                <Icon style={{ fontSize: '6px' }} type="close" />
              </a>{' '}
              风险场景
            </div>
          ),
          dataIndex: 'riskScene',
          key: '风险场景',
          render: riskScene => {
            const isLong = riskScene.length > 10;
            return (
              <span>
                {isLong ? (
                  <Tooltip title={riskScene}>`${riskScene.slice(0, 10)}...`</Tooltip>
                ) : (
                  <span>{riskScene}</span>
                )}
              </span>
            );
          },
        },
        {
          title: (
            <div>
              <a onClick={() => this.columsControl('department')}>
                <Icon style={{ fontSize: '6px' }} type="close" />
              </a>{' '}
              部门
            </div>
          ),
          dataIndex: 'department',
          key: '部门',
          render: dep => {
            const isLong = dep.length > 10;
            return (
              <span>
                {isLong ? (
                  <Tooltip title={dep}>`${dep.slice(0, 10)}...`</Tooltip>
                ) : (
                  <span>{dep}</span>
                )}
              </span>
            );
          },
        },
        {
          title: (
            <div>
              <a onClick={() => this.columsControl('createTime')}>
                <Icon style={{ fontSize: '6px' }} type="close" />
              </a>{' '}
              告警时间
            </div>
          ),
          dataIndex: 'createTime',
          key: '告警时间',
        },
        {
          title: (
            <div>
              <a onClick={() => this.columsControl('status')}>
                <Icon style={{ fontSize: '6px' }} type="close" />
              </a>{' '}
              状态
            </div>
          ),
          dataIndex: 'status',
          key: '状态',
          render: status => (
            <Tag color={ABNORMAL_AUDIT_STATUS_COLOR[status]}>{ABNORMAL_AUDIT_STATUS[status]}</Tag>
          ),
        },
        {
          title: (
            <div>
              <a onClick={() => this.columsControl('baseInfo')}>
                <Icon style={{ fontSize: '6px' }} type="close" />
              </a>
              文件名
            </div>
          ),
          dataIndex: 'baseInfo',
          key: '文件名',
          render: text => {
            const jsonData = JSON.parse(text);
            const name = jsonData.filename;
            return name ? <span>{name}</span> : '';
          },
        },
        {
          title: (
            <div>
              <a onClick={() => this.columsControl('operatePlatform')}>
                <Icon style={{ fontSize: '6px' }} type="close" />
              </a>
              操作平台
            </div>
          ),
          dataIndex: 'operatePlatform',
          key: '操作平台',
        },
        {
          title: '操作',
          fixed: 'right',
          width: 80,
          render: (_, record) => (
            <div>
              {record.status === 0 ? (
                <RoamMoudle onOk={this.pushRoma}>
                  <a
                    onClick={() => {
                      this.roamId(record.id);
                    }}
                  >
                    流转
                  </a>
                </RoamMoudle>
              ) : (
                <span>流转</span>
              )}
            </div>
          ),
        },
      ],
    };
  }

  componentWillMount() {
    const { dispatch } = this.props;
   dispatch({
        type: 'abnormalList/fetchList',
        payload: {
          page: 1,
          pageSize: 10,
          filter: [],
        },
      });
  }

  columsControl = str => {
    const { colKey, columns, newCol } = this.state;
    const id = colKey[str];
    newCol.push(columns[id]);
    delete columns[id];  // 此处用delete方便后续添加某项表头的时候能回到最开始的位置
    this.setState({ columns, newCol });
  };

  addCol = (one, str, i) => {
    const { colKey, columns, newCol } = this.state;
    const id = colKey[str];
    columns.splice(id, 1, one);  // 替换
    newCol.splice(i, 1); // 删除
    this.setState({ columns, newCol });
  };

  handleTableChange = (pagination, filters, sorter) => {
    const { current, pageSize } = pagination;
    const {
      dispatch,
      abnormalList: { filter },
    } = this.props;
    dispatch({
      type: 'abnormalList/fetchList',
      payload: {
        page: current,
        pageSize,
        filter,
        sorter,
      },
    });
  };

 
  render() {
    const { abnormalList, loading } = this.props;
    const { selectedData, columns, newCol } = this.state;

    const { data, page, total } = abnormalList;

    const rowSelection = {
      onChange: (selectedRowKeys, selectedRows) => {
        console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
        this.setState({ selectedData: selectedRowKeys });
      },
      getCheckboxProps: record => ({
        disabled: record.name === 'Disabled User', // Column configuration not to be checked
        name: record.name,
      }),
    };

    return (
      <GridContent>
        <Card bordered={false}>
          <div
            style={{
              border: '1px solid #CAE7FD',
              padding: '5px 10px',
              borderRadius: '4px',
              background: '#E9F7FE',
            }}
          >
         可添加表头:
            {newCol.map((item, index) => (
              <Tag key={item.dataIndex}>
                <a
                  onClick={() => {
                    this.addCol(item, item.dataIndex, index);
                  }}
                >
                  +{item.key}
                </a>
              </Tag>
            ))}
          </div>
          <br />
          <Table
            columns={columns}
            dataSource={data}
            loading={loading}
            rowSelection={rowSelection}
             scroll={{ x: 1300 }}
            rowKey="id"
            pagination={{
              showSizeChanger: true,
              current: page,
              total,
              pageSizeOptions: ['10', '20', '50', '100'],
            }}
            onChange={this.handleTableChange}
          />
        </Card>
      </GridContent>
    );
  }
}

export default AbnormalList;

  

主要是在columns 中的title中添加点击事件。columsControl,addCol两个函数是实现的关键。

 

转载请说明来源,谢谢

posted @ 2020-12-15 13:07  荷风伊夏  阅读(1681)  评论(0编辑  收藏  举报