效果图:

 

 

在线demo

代码:直接复制黏贴就可以运行

import React, { useState } from "react";
import { Form, Input, Table, Typography } from "antd";
import { message, Button } from "antd";
import styles from "./styles.css";
const isEditing = (record) => {
  return record.editable;
};
const EditableCell = ({
  editing,
  dataIndex,
  title,
  inputType,
  record,
  index,
  children,
  ...restProps
}) => {
  const inputNode = <Input autoComplete="off" />;
  return (
    <td {...restProps}>
      {editing ? (
        <Form.Item
          name={dataIndex}
          style={{
            margin: 0
          }}
          rules={[
            {
              required: true,
              message: `请输入${title}!`
            }
          ]}
        >
          {inputNode}
        </Form.Item>
      ) : (
        children
      )}
    </td>
  );
};

const Demo = () => {
  const [data, setData] = useState([]); //存放表格内容
  const [form] = Form.useForm();
  const [editingKey, setEditingKey] = useState("");

  const edit = async (record) => {
    form.setFieldsValue({
      personName: "",
      companyName: "",
      recommendedTime: "",
      editable: true,
      ...record
    });
    setEditingKey(record.key);
    //切换成编辑状态
    const newData = [...data];
    const index = newData.findIndex((item) => record.key === item.key);
    if (index > -1) {
      const item = newData[index];
      item.editable = true;
      newData.splice(index, 1, { ...item });
    }
  };

  const cancel = (key) => {
    const newData = [...data];
    const index = newData.findIndex((item) => key === item.key);
    if (index > -1) {
      const item = newData[index];
      item.editable = false;
      newData.splice(index, 1, { ...item });
      setData(newData);
      setEditingKey("");
    }
  };

  const save = async (key) => {
    try {
      const row = await form.validateFields();
      const newData = [...data];
      const index = newData.findIndex((item) => key === item.key);

      if (index > -1) {
        const item = newData[index];
        item.editable = false;
        newData.splice(index, 1, { ...item, ...row });
        setData(newData);
        setEditingKey("");
      } else {
        newData.push(row);
        setData(newData);
        setEditingKey("");
      }
    } catch (errInfo) {
      console.log("保存失败", errInfo);
    }
  };
  const columns = [
    {
      title: "推荐的人才",
      dataIndex: "personName",
      width: "25%",
      editable: true
    },
    {
      title: "入驻的企业",
      dataIndex: "companyName",
      width: "40%",
      editable: true
    },
    {
      title: "推荐时间",
      dataIndex: "recommendedTime",
      width: "15%",
      editable: true
    },
    {
      title: "操作",
      dataIndex: "operation",
      render: (_, record) => {
        const editable = isEditing(record);
        return editable ? (
          <span>
            <a
              onClick={() => save(record.key)}
              style={{
                marginRight: 8
              }}
            >
              保存
            </a>
            <a onClick={() => cancel(record.key)}>取消</a>
          </span>
        ) : (
          <Typography.Link
            disabled={editingKey !== ""}
            onClick={() => edit(record, record.key)}
          >
            编辑
          </Typography.Link>
        );
      }
    }
  ];

  // 依据是否可编辑返回不同元素
  const mergedColumns = columns.map((col) => {
    if (!col.editable) {
      return col;
    }
    return {
      ...col,
      onCell: (record) => ({
        record,
        inputType: col.dataIndex === "age" ? "number" : "text",
        dataIndex: col.dataIndex,
        title: col.title,
        editing: isEditing(record)
      })
    };
  });
  const add = () => {
    const index = data.some((item) => item.editable === true);
    if (index) {
      message.error("存在空白项");
      return;
    }
    form.resetFields();
    data.push({
      key: "" + data.length,
      personName: "",
      companyName: "",
      recommendedTime: "",
      editable: true
    });
    setData([...data]);
  };

  return (
    <div>
      <div className={styles.tableWrapper}>
        <Form form={form} component={false}>
          <Table
            components={{
              body: {
                cell: EditableCell
              }
            }}
            bordered
            dataSource={data}
            columns={mergedColumns}
            rowClassName="editable-row"
            pagination={false}
          />
        </Form>
      </div>
      <div className={styles.btn} style={{ width: "100%" }}>
        {(data.some((item) => item.editable === true) && (
          <Button disabled type="primary" block>
            添加新行
          </Button>
        )) || (
          <Button type="primary" block onClick={add}>
            添加新行
          </Button>
        )}
      </div>
    </div>
  );
};
export default Demo;

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐