index.js 6.13 KB
Newer Older
duanledexianxianxian's avatar
duanledexianxianxian committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241
import React from 'react';
import { Table, Popconfirm, Form, Icon } from 'antd';
import { EditableContext, EditableCell } from './EditableCell';
import styles from './index.less';

class EditableTable extends React.Component {
  static defaultProps = {
    pageSize: 10,
  };

  constructor(props) {
    super(props);
    const { dataSource } = props;
    this.state = {
      data: dataSource,
      editingKey: '',
    };
    this.actionColumns = [
      {
        title: '操作',
        width: 80,
        dataIndex: 'operation',
        render: (text, record) => {
          const { editingKey } = this.state;
          const editable = this.isEditing(record);
          const showDelete = this.showDelete(record, editable);
          return (
            <div>
              {editable ? (
                <span>
                  <EditableContext.Consumer>
                    {form => (
                      <a onClick={e => this.save(e, form, record)} style={{ marginRight: 8 }}>
                        <Icon type="save" theme="filled" />
                      </a>
                    )}
                  </EditableContext.Consumer>
                  <Popconfirm title="确定取消?" onConfirm={() => this.cancel(record)}>
                    <a>
                      <Icon type="stop" theme="filled" />
                    </a>
                  </Popconfirm>
                </span>
              ) : (
                <a
                  disabled={editingKey !== ''}
                  // 进入可编辑
                  onClick={() => this.edit(record.key)}
                >
                  <Icon
                    type="edit"
                    theme="filled"
                    twoToneColor={editingKey !== '' && '#bec5d4'}
                    className={styles.disable}
                  />
                </a>
              )}
              {showDelete && (
                <Popconfirm title="确定删除?" onConfirm={() => this.delete(record)}>
                  <a style={{ marginLeft: 8 }}>
                    <Icon type="delete" theme="filled" />
                  </a>
                </Popconfirm>
              )}
            </div>
          );
        },
      },
    ];
  }

  // componentWillReceiveProps
  componentWillReceiveProps(nextProps) {
    const { dataSource } = this.props;
    if (dataSource !== nextProps.dataSource) {
      this.setState({ data: nextProps.dataSource });
    }
  }

  // 是否显示删除按钮
  showDelete = (record, editable) => {
    if (record.action === 'add' || editable) {
      return false;
    }
    return true;
  };

  // eslint-disable-next-line react/destructuring-assignment
  isEditing = record => record.key === this.state.editingKey;

  // change
  onChangeTable = (pagination, filters, sorter) => {
    const { onChangeTable } = this.props;
    if (onChangeTable && onChangeTable instanceof Function) {
      onChangeTable(pagination, filters, sorter);
    }
    this.cancel();
  };

  // 删除
  delete = async record => {
    const { onDelete, total, pageNum, pageSize } = this.props;
    if (onDelete instanceof Function) {
      // do someting
      const goPrePage = total === (pageNum - 1) * pageSize + 1;
      onDelete({ ...record, goPrePage }).then(() => {
        this.cancel();
      });
    }
  };

  // 增加行
  addRow = row => {
    const { dataSource } = this.props;
    const newData = [...dataSource];
    newData.splice(0, 0, row);
    this.setState({
      editingKey: row.key,
      data: newData,
    });
    setTimeout(() => {
      document
        .querySelectorAll('tr[data-row-key]:first-child')[0]
        .getElementsByTagName('input')[0]
        .focus();
    }, 800);
  };

  // 取消
  cancel = record => {
    const { data } = this.state;
    if (record && record.action === 'add') {
      // 去掉第一条记录
      const newData = [...data];
      newData.splice(0, 1);
      this.setState({
        data: newData,
      });
    }
    this.setState({
      editingKey: '',
    });
  };

  /**
   * 编辑
   * @param {*} key
   */
  edit(key) {
    this.setState({
      editingKey: key,
    });
  }

  /**
   * 保存
   * @param {*} form
   * @param {*} key
   */
  save(e, form, record) {
    e.preventDefault();
    form.validateFields((error, row) => {
      if (error) {
        return;
      }
      // 新增需要刷新页面  编辑可不刷新页面
      const { onAdd, onEdit } = this.props;
      if (record.action === 'add') {
        if (onAdd instanceof Function) {
          onAdd({ ...record, ...row }).then(result => {
            if (result) {
              this.setState({
                editingKey: '',
              });
            }
          });
        }
      } else if (onEdit instanceof Function) {
        onEdit({ ...record, ...row }).then(result => {
          if (result) {
            this.setState({
              editingKey: '',
            });
          }
        });
      }
    });
  }

  render() {
    const { data } = this.state;
    const { form, pageData, loading, columns = [] } = this.props;
    const components = {
      body: {
        cell: EditableCell,
      },
    };

    const cols = columns.concat(this.actionColumns).map(col => {
      if (!col.editable) {
        return col;
      }
      return {
        ...col,
        onCell: record => ({
          renderEditing: col.renderEditing,
          record,
          rules: col.rules,
          dataIndex: col.dataIndex,
          title: col.title,
          editing: this.isEditing(record),
        }),
      };
    });

    return (
      <div className={styles.root}>
        <EditableContext.Provider value={form}>
          <Table
            className="fixedWidthTable"
            // scroll={{ x: 1300 }}
            components={components}
            dataSource={data}
            columns={cols}
            loading={loading}
            onChange={this.onChangeTable}
            rowClassName="editable-row"
            pagination={{
              ...pageData,
              showQuickJumper: true,
              showSizeChanger: true,
            }}
          />
        </EditableContext.Provider>
      </div>
    );
  }
}

const EditableFormTable = Form.create()(EditableTable);
export default EditableFormTable;