基于Ant Design的Table组件封装

        可以帮助在项目中更方便地复用和管理表格。下面提供jsx和tsx两种类型的:


1、首先,在你的src/components目录下创建CustomTable.jsx文件,用于封装Table组件。

import React, { useState, useEffect } from 'react';
import { Table, Spin } from 'antd';
import PropTypes from 'prop-types';

const CustomTable = ({
  columns,
  fetchData,     // 一个用于获取数据的函数
  pagination,    // 分页配置
  rowKey,        // 每行的唯一标识
  ...restProps   // 其他Table组件的props
}) => {
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(false);
  const [currentPagination, setCurrentPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
    ...pagination,
  });

  // 获取数据
  const loadData = async (paginationConfig = currentPagination) => {
    setLoading(true);
    try {
      const response = await fetchData(paginationConfig);
      setData(response.data);
      setCurrentPagination({
        ...paginationConfig,
        total: response.total,
      });
    } catch (error) {
      console.error('Error fetching table data:', error);
    } finally {
      setLoading(false);
    }
  };

  // 页面加载时和分页、排序、过滤条件改变时触发数据加载
  useEffect(() => {
    loadData();
  }, [currentPagination.current, currentPagination.pageSize]);

  const handleTableChange = (pagination) => {
    setCurrentPagination({
      ...currentPagination,
      current: pagination.current,
      pageSize: pagination.pageSize,
    });
  };

  return (
    <Spin spinning={loading}>
      <Table
        columns={columns}
        dataSource={data}
        pagination={currentPagination}
        onChange={handleTableChange}
        rowKey={rowKey}
        {...restProps}
      />
    </Spin>
  );
};

CustomTable.propTypes = {
  columns: PropTypes.array.isRequired,
  fetchData: PropTypes.func.isRequired,
  pagination: PropTypes.object,
  rowKey: PropTypes.string.isRequired,
};

export default CustomTable;

2、TS格式封装

import React, { useState, useEffect } from 'react';
import { Table, Spin, TableProps, PaginationConfig } from 'antd';
import { ColumnsType } from 'antd/es/table';
import { TablePaginationConfig } from 'antd/es/table';
import { AxiosResponse } from 'axios';  // 假设你用的是 axios 来获取数据,可以根据你的情况替换

interface CustomTableProps<T> extends Omit<TableProps<T>, 'columns' | 'dataSource'> {
  columns: ColumnsType<T>;
  fetchData: (pagination: TablePaginationConfig) => Promise<AxiosResponse<{ data: T[]; total: number }>>;
  pagination?: PaginationConfig;
  rowKey: string;
}

const CustomTable = <T extends object>({
  columns,
  fetchData,
  pagination,
  rowKey,
  ...restProps
}: CustomTableProps<T>): JSX.Element => {
  const [data, setData] = useState<T[]>([]);
  const [loading, setLoading] = useState(false);
  const [currentPagination, setCurrentPagination] = useState<TablePaginationConfig>({
    current: 1,
    pageSize: 10,
    total: 0,
    ...pagination,
  });

  // 获取数据
  const loadData = async (paginationConfig = currentPagination) => {
    setLoading(true);
    try {
      const response = await fetchData(paginationConfig);
      setData(response.data.data);
      setCurrentPagination({
        ...paginationConfig,
        total: response.data.total,
      });
    } catch (error) {
      console.error('Error fetching table data:', error);
    } finally {
      setLoading(false);
    }
  };

 
  useEffect(() => {
    loadData();
  }, [currentPagination.current, currentPagination.pageSize]);

  const handleTableChange = (pagination: TablePaginationConfig) => {
    setCurrentPagination({
      ...currentPagination,
      current: pagination.current,
      pageSize: pagination.pageSize,
    });
  };

  return (
    <Spin spinning={loading}>
      <Table<T>
        columns={columns}
        dataSource={data}
        pagination={currentPagination}
        onChange={handleTableChange}
        rowKey={rowKey}
        {...restProps}
      />
    </Spin>
  );
};

export default CustomTable;

3. 说明

  • 泛型 T: 使得 CustomTable 组件能够处理不同的数据结构。你可以使用 <CustomTable<DataType>> 来指定表格的行数据类型。
  • fetchData 函数: 接收分页配置并返回一个包含数据和总数的 Promise。你可以根据实际情况修改数据获取的方式。
  • columns: 表格的列配置。
  • rowKey: 指定表格行的唯一标识属性。

可以根据需求进一步扩展这个 CustomTable 组件,比如:

  • 添加更多的数据处理逻辑,比如排序、过滤等。
  • 添加行选择、批量操作等功能。
  • 集成更多的 UI 特性,如自定义行样式、行操作按钮等。
封装Table组件可以使代码更加简洁、易读,并且可以复用。以下是一个简单的封装Table组件的示例: ``` import React from 'react'; import PropTypes from 'prop-types'; import { Table } from 'antd'; const CustomTable = ({ columns, dataSource, loading, pagination }) => { return ( <Table columns={columns} dataSource={dataSource} loading={loading} pagination={pagination} /> ); }; CustomTable.propTypes = { columns: PropTypes.array.isRequired, dataSource: PropTypes.array.isRequired, loading: PropTypes.bool.isRequired, pagination: PropTypes.object.isRequired, }; export default CustomTable; ``` 在这个示例中,我们使用了Ant DesignTable组件,并将其封装为CustomTable组件。CustomTable组件接收四个props:columns(表格列的配置描述)、dataSource(表格数据)、loading(表格是否正在加载)和pagination(分页器的配置项)。这些props都是必需的,并且我们使用PropTypes对其进行了类型检查。 使用CustomTable组件时,只需要像下面这样传入props即可: ``` import React from 'react'; import CustomTable from './CustomTable'; const columns = [ { title: 'Name', dataIndex: 'name', key: 'name', }, { title: 'Age', dataIndex: 'age', key: 'age', }, ]; const dataSource = [ { key: '1', name: 'John Brown', age: 32, }, { key: '2', name: 'Jim Green', age: 42, }, ]; const pagination = { pageSize: 10, }; const Example = () => { return ( <CustomTable columns={columns} dataSource={dataSource} loading={false} pagination={pagination} /> ); }; export default Example; ``` 以上就是一个简单的封装Table组件的示例。根据实际需求,可以在CustomTable组件中添加更多的props和配置项。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一直在学习的小白~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值