如何创建可重用的 antd table react

how create a reusable antd table react

我正在使用 antd react 框架,我有很多组件呈现 antd tablepaginationsorting,所以我决定制作一个可重复使用的 table 我不想在下面的实现中每次需要 table 时都重复自己 我成功加载了 table, 但分页和排序无法正常工作,谁能帮帮我,

这是我尝试过的可重用 table 组件 (useTable.jsx) :-

import { Table } from 'antd';
import React, { useEffect, useState } from 'react';

export function useTable(columns, data, fetchData, loading) {
  

  const handleTableChange = (newPagination, filters, sorter) => {
    fetchData({
      sortField: sorter.field,
      sortOrder: sorter.order,
      pagination: newPagination,
      ...filters,
    });
  };

  const TableContainer = () => (
    <Table columns={columns} dataSource={data} loading={loading} onChange={handleTableChange} />
  );
  return { TableContainer };
}

父组件使用table:-

import React, { useEffect, useState } from 'react';
import qs from 'qs';
import { Table, Card, Button, Input, Space } from 'antd';
import styles from './Class.less';
import { useTable } from '../../../components/common/useTable';
const columns = [
  {
    title: 'Name',
    dataIndex: 'name',
    sorter: true,
    render: (name) => `${name.first} ${name.last}`,
    width: '20%',
  },
  {
    title: 'Gender',
    dataIndex: 'gender',
    filters: [
      {
        text: 'Male',
        value: 'male',
      },
      {
        text: 'Female',
        value: 'female',
      },
    ],
    width: '20%',
  },
  {
    title: 'other',
    dataIndex: 'other',
    sorter: true,
  },

  {
    title: 'Action',
    dataIndex: 'email',
    render: () => (
      <Space>
        <a color="yellow" onClick={() => alert('edit')}>
          Edit
        </a>
        <a color="yellow" onClick={() => alert('delete')}>
          Delete
        </a>
      </Space>
    ),
  },
];

const getRandomuserParams = (params) => ({
  results: params.pagination?.pageSize,
  page: params.pagination?.current,
  ...params,
});
const Classes = () => {
  const [data, setData] = useState();
  const [loading, setLoading] = useState(false);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
  });

  const fetchData = (params = {}) => {
    setLoading(true);
    fetch(`https://randomuser.me/api?${qs.stringify(getRandomuserParams(params))}`)
      .then((res) => res.json())
      .then(({ results }) => {
        setData(results);
        setLoading(false);
        setPagination({
          ...params.pagination,
          total: 200, // 200 is mock data, you should read it from server
          // total: data.totalCount,
        });
      });
  };

  const { TableContainer } = useTable(columns, data, fetchData, loading);

  useEffect(() => {
    fetchData({
      pagination,
    });
  }, []);

  return (
    <Card className={styles.card}>
      <TableContainer
        columns={columns}
        rowKey={(record) => record.login.uuid}
        dataSource={data}
        loading={loading}
      />
    </Card>
  );
};

export default Classes;

谢谢!

你能尝试像下面这样向 useTable 挂钩添加分页属性吗?


export function useTable(columns, data, fetchData, loading, pagination) {
  const handleTableChange = (newPagination, filters, sorter) => {
    fetchData({
      sortField: sorter.field,
      sortOrder: sorter.order,
      pagination: newPagination,
      ...filters
    });
  };

  const TableContainer = () => (
    <Table
      columns={columns}
      rowKey={(record) => record.login.uuid}
      dataSource={data}
      loading={loading}
      onChange={handleTableChange}
      pagination={pagination}
    />
  );
  return { TableContainer };
}

您能验证一下您的组件中的 TableContainer 是否如下所示。

 const { TableContainer } = useTable(
    columns,
    data,
    fetchData,
    loading,
    pagination
  );

你的组件 returns:

return (
    <Card>
      <TableContainer
        columns={columns}
        rowKey={(record) => record.login.uuid}
        dataSource={data}
        loading={loading}
        pagination={pagination}
      />
    </Card>
  );

我自己想出来的,这是我的解决方案

export function useTable(columns, data) {
  const [page, setPage] = useState(1);

  const handlePageChange = (newpage) => {
    setPage(newpage);
  };

  const TableContainer = ({ loading }) => (
    <Table
      columns={columns}
      dataSource={data}
      pagination={{
        current: page,
        pageSize: 6,
        total: data?.length,
        onChange: (page) => handlePageChange(page),
        size: 'medium',
      }}
      loading={loading}
    />
  );
  return { TableContainer };

}

我的组件:-

 return (
    <Card className={styles.card}>
      <TableContainer columns={columns} rowKey={(record) => record.login.uuid} dataSource={data} />
    </Card>
  );