【antd】自定義實現可編輯表格

之前用table組件的時候看到antd中的一個可編輯表格的實現,如下圖:


使用的時候發現了一些問題:第一個是這個Table組件不支持多個編輯,官方版的只支持編輯的時候只編輯一個,且更不支持一鍵保存,第二個問題是官方代碼是form組件和table組件合一起的,不夠接地氣(怪就怪自己太菜了,有點看不懂....)


所以準備自己手擼一個支持多條編輯以及一鍵保存的Table組件供看不懂官方代碼的小白們使用。

最後出來的效果如下:(請忽略樣式

代碼如下:

// 單行可編輯
import React from "react";
import { Table, Input, Button } from "antd";
export default class EditTable extends React.Component {
  state = {
    dataSource: [],
    editArr: [],
  };
  componentDidMount() {
    let arr = [];
    for (let i = 1; i < 11; i++) {
      arr.push({
        id: i,
        name: `第${i}個名字`,
        age: i,
        address: `住在第${i}號`,
      });
    }
    this.setState({ dataSource: arr });
  }

  // 渲染出來input,輸入的時候改變dataSource的數據
  renderInput = (text, record, index, field) => {
    const { editArr } = this.state;
    return record.edit ? (
      <Input
        value={
          editArr[index] && editArr[index][field]
            ? editArr[index][field]
            : record[field]
        }
        onChange={(e) => this.inputChange(e, record, index, field)}
        // onPressEnter={(e) => this.handleSave(e, record)}
        // onBlur={(e) => this.handleSave(e, record)}
      />
    ) : (
      text
    );
  };

  // 編輯表格
  edit = (record, id) => {
    const { dataSource } = this.state;
    // 淺拷貝下數據
    const newArr = [...dataSource];
    // 找到index的值
    const index = newArr.findIndex((item) => item.id === id);
    // 利用splice方法刪除原數據,新增新數據
    newArr.splice(index, 1, { ...record, edit: true });
    // 注意:一開始寫法是const arr = newArr.splice(index, 1, { ...record, ...{ edit: true } });是錯的,因爲這個方法返回的是刪除的那一條值
    this.setState({ dataSource: newArr });
  };

  // input改變的時候
  inputChange = (e, record, index, field) => {
    let { editArr } = this.state;
    editArr[index] = record;
    record[field] = e.target.value;
    this.setState({ editArr });
  };

  // 一鍵保存所有數據
  saveAll = () => {
    const { dataSource } = this.state;
    const arr = dataSource.map((item) => {
      return {
        ...item,
        edit: false,
      };
    });
    this.setState({ dataSource: arr }, () => {
      console.log(dataSource, "--dataSource");
    });
  };

  // 單條保存
  handleSave = (record, index) => {
    const { editArr, dataSource } = this.state;
    const newData = [...dataSource];
    // 用splice不改變原來的數組順序
    newData.splice(index, 1, {
      ...record,
      ...editArr[index],
      edit: false,
    });
    this.setState({ dataSource: newData });
  };

  render() {
    const columns = [
      {
        title: "姓名",
        dataIndex: "name",
        key: "name",
        render: (text, record, index) =>
          this.renderInput(text, record, index, "name"),
      },
      {
        title: "年齡",
        dataIndex: "age",
        key: "age",
        render: (text, record, index) =>
          this.renderInput(text, record, index, "age"),
      },
      {
        title: "住址",
        dataIndex: "address",
        key: "address",
        render: (text, record, index) =>
          this.renderInput(text, record, index, "address"),
      },
      {
        title: "操作",
        dataIndex: "edit",
        key: "edit",
        render: (text, record, index) => {
          return !record.edit ? (
            <span
              style={{ color: "black", cursor: "pointer" }}
              onClick={() => this.edit(record, record.id)}
            >
              編輯
            </span>
          ) : (
            <span
              style={{ color: "blue", cursor: "pointer" }}
              onClick={() => this.handleSave(record, index)}
            >
              單條保存
            </span>
          );
        },
      },
    ];

    return (
      <div style={{ width: "90%" }}>
        <Table
          rowKey={(record) => record.id}
          dataSource={this.state.dataSource}
          columns={columns}
        />
        <Button type="primary" onClick={this.saveAll}>
          一鍵保存
        </Button>
      </div>
    );
  }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章