美文网首页
【antd】自定义实现可编辑表格

【antd】自定义实现可编辑表格

作者: 废柴码农 | 来源:发表于2020-10-26 15:22 被阅读0次

之前用table组件的时候看到antd中的一个可编辑表格的实现,如下图:


image.png

使用的时候发现了一些问题:第一个是这个Table组件不支持多个编辑,官方版的只支持编辑的时候只编辑一个,且更不支持一键保存,第二个问题是官方代码是form组件和table组件合一起的,不够接地气(怪就怪自己太菜了,有点看不懂....)

image.png
所以准备自己手撸一个支持多条编辑以及一键保存的Table组件供看不懂官方代码的小白们使用。

最后出来的效果如下:(请忽略样式

可编辑表格.gif

代码如下:

// 单行可编辑
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>
    );
  }
}

相关文章

网友评论

      本文标题:【antd】自定义实现可编辑表格

      本文链接:https://www.haomeiwen.com/subject/mkmamktx.html