antd表格监听滚动条触底
import { useRef } from 'react';
import { Table } from 'antd';
import ReactDOM from 'react-dom';
interface DataType {
key: string;
name: string;
age: number;
address: string;
tags: string[];
}
const scrollRef = useRef<any>();
const columns: ColumnsType<DataType> = [
{
title: 'Name',
dataIndex: 'name',
key: 'name',
render: (text) => <a>{text}</a>,
},
{
title: 'Age',
dataIndex: 'age',
key: 'age',
},
{
title: 'Address',
dataIndex: 'address',
key: 'address',
},
{
title: 'Tags',
key: 'tags',
dataIndex: 'tags',
render: (_, { tags }) => (
<>
{tags.map((tag) => {
let color = tag.length > 5 ? 'geekblue' : 'green';
if (tag === 'loser') {
color = 'volcano';
}
return (
<Tag color={color} key={tag}>
{tag.toUpperCase()}
</Tag>
);
})}
</>
),
}
];
const data: DataType[] = [];
for( var i = 0;i < 10;i++){
data.push({
key: i,
name: name+i,
age: 32,
address: 'Sydney No. 1 Lake Park',
tags: ['cool', 'teacher'],
});
}
const getData = () = > {
for( var i = 0;i < 20;i++){
data.push({
key: i,
name: name+i,
age: 32,
address: 'Sydney No. 1 Lake Park',
tags: ['cool', 'teacher'],
});
}
}
const onScrollEvent = () => {
if (dataLoadl) {
return;
}
const table = ReactDOM.findDOMNode(scrollRef.current);
const tableBody = (table as Element)?.querySelector('.ant-table-body');
const tableBodyHeight: number = tableBody?.clientHeight ? tableBody?.clientHeight : 0;
const contentHeight = tableBody?.scrollHeight ? tableBody?.scrollHeight : 0;
const toTopHeight = tableBody?.scrollTop ? tableBody?.scrollTop : 0;
if (toTopHeight === 0 || data.length <= 10) {
return;
}
if (contentHeight - (toTopHeight + tableBodyHeight) <= 1) {
if (tableData.length == data.length) {
scorll = false;
message.info('没有更多数据了');
setDataLoad(false);
return;
} else {
setDataLoad(true);
getData();
}
}
}
return(
<div onScrollCapture={onScrollEvent}>
<Table columns={column} dataSource={data} pagination={false} ref={(c) => { scrollRef.current = c }}/>
</div>
)