Ant Design 表格中的滚动页面

问题描述 投票:0回答:1

我有一个来自 ANTD 的表格,它有很多页,因为我已经为它定义了分页, 我希望它也可以滚动,并在用户滚动到表格底部时转到下一页。

这是我的组件:

 <Table columns={columns} dataSource={filteredData}
                title={() => <>  <h3>title</h3>}
                rowClassName="rowClassName"
                pagination={{
                    onChange: cancel,
                }}
            />

我该怎么做?

reactjs scroll antd
1个回答
0
投票

检查可滚动容器

.ant-table-body
是否到达底部,如果滚动条到达底部,则转到下一页。

import React, { useEffect, useLayoutEffect, useState } from 'react';
import './index.css';
import { Table } from 'antd';
import type { TableColumnsType } from 'antd';

interface DataType {
  key: React.Key;
  name: string;
  age: number;
  address: string;
}

const columns: TableColumnsType<DataType> = [
  {
    title: 'Name',
    dataIndex: 'name',
    width: 150,
  },
  {
    title: 'Age',
    dataIndex: 'age',
    width: 150,
  },
  {
    title: 'Address',
    dataIndex: 'address',
  },
];

const data: DataType[] = [];
for (let i = 0; i < 100; i++) {
  data.push({
    key: i,
    name: `Edward King ${i}`,
    age: 32,
    address: `London, Park Lane no. ${i}`,
  });
}

function calculatePage(pageSize: number, total: number) {
  return Math.floor((total - 1) / pageSize) + 1;
}

const allPage = calculatePage(10, data.length);

const App: React.FC = () => {
  const [pagination, setPagination] = useState({ current: 1, pageSize: 10 });

  useEffect(() => {
    const $tableBody = document.querySelector('.ant-table-body');
    const onScroll = () => {
      if (
        Math.abs(
          $tableBody.scrollHeight -
            $tableBody.scrollTop -
            $tableBody.clientHeight
        ) < 1
      ) {
        console.log('reach bottom');
        if (pagination.current < allPage) {
          setPagination((pre) => ({ ...pre, current: pre.current + 1 }));
        }
      }
    };
    if ($tableBody) {
      $tableBody.addEventListener('scroll', onScroll);
    }

    return () => {
      if ($tableBody) {
        $tableBody.removeEventListener('scroll', onScroll);
      }
    };
  }, [pagination]);

  // scroll to top when pagination changes
  useLayoutEffect(() => {
    const $tableBody = document.querySelector('.ant-table-body');
    if ($tableBody) {
      $tableBody.scrollTop = 0;
    }
  }, [pagination]);

  return (
    <Table
      columns={columns}
      dataSource={data}
      total={data.length}
      pagination={pagination}
      onChange={(pagination) => {
        setPagination(pagination);
      }}
      scroll={{ y: 240 }}
    />
  );
};

export default App;

堆栈闪电战

© www.soinside.com 2019 - 2024. All rights reserved.