记录 Hooks Table 增删子表

记录Antd Table组件写法父表Row增加、删除或其他操作子表单独刷新

平常我们的做表格都有展开子表,那么我们要在父元素操作子元素比如删除、增加和刷新,这种情况我们需要做如下写法:

image.png
import { Table, Row, Space, Button, Spin } from "antd";
import Mock from "mockjs";
import { useState, memo, useEffect } from "react";

//子元素
const RefreshChildRow = memo((props) => {
  const { id, refreshId, resetRefresh } = props;
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    if (refreshId === id) {
      setLoading(true);
      setTimeout(() => {
        setLoading(false);
        resetRefresh(null);
      }, 1000);
    }
  }, [refreshId, id, resetRefresh]);

  return (
    <Spin spinning={loading}>
      <Row>{props.name}</Row>
    </Spin>
  );
});

const Random = Mock.Random;

const data = new Array(10).fill("").map(() => ({
  name: Random.name(),
  id: Mock.mock("@increment"),
  title: Random.title(),
  child: [
    {
      name: Random.name(),
      id: Mock.mock("@increment"),
      title: Random.title()
    }
  ]
}));

const CustomTable = (props) => {
  const [refreshId, setRefreshId] = useState(null);
  const handleAdd = (row) => {
    setRefreshId(row.id);
  };
  const columns = [
    {
      dataIndex: "name",
      title: "name"
    },
    {
      dataIndex: "id",
      title: "id"
    },
    {
      dataIndex: "title",
      title: "title"
    },
    {
      title: "操作",
      render(row) {
        return (
          <Space>
            <Button onClick={() => handleAdd(row)}>添加</Button>
          </Space>
        );
      }
    }
  ];
  return (
    <Table
      columns={columns}
      rowKey={"id"}
      pagination={false}
      size="small"
      dataSource={data}
      expandable={{
        expandedRowRender: (record) => (
          <RefreshChildRow
            {...record}
            refreshId={refreshId}
            resetRefresh={setRefreshId}
          />
        )
      }}
    />
  );
};

export default memo(CustomTable);

推荐阅读更多精彩内容