直接在Table组件外面包一个div,通过这个div的滚动事件onScrollCapture来实现
import React, { useState, useEffect } from 'react';
import { Table } from 'antd';
import api from 'api/api';
const ListPage = (props) => {
const [isMore, setIsMore] = useState(true); // 是否还有数据
const [page, setPage] = useState(1); // 页码
const [rows, setRows] = useState(10); // 每页10条
const [total, setTotal] = useState(0); // 总条数
const [dataSource, setDataSource] = useState([]); // 数据
let scrollRef;
const getList = (page = 1) => {
api
.list({ page, rows })
.then((res) => {
const { data } = res.data;
if (data) {
const { total, rows } = data;
setTotal(total);
setDataSource(page == 1 ? rows : [...dataSource, ...rows]);
}
});
};
const onScrollCapture = (e) => {
// scrollTop会有小数点导致等式不成立,解决方案:四舍五入
if (
Math.round(scrollRef.scrollTop) + scrollRef.clientHeight == scrollRef.scrollHeight
) {
if (Math.ceil(total / rows) == page) {
setIsMore(false);
return false;
}
getList(page + 1);
setPage(page + 1);
}
};
const columns = [
{
title: '序号',
dataIndex: 'rownum',
key: 'rownum',
width: '15%',
render: (text, record, index) => index + 1
},
{
title: '姓名',
dataIndex: 'name',
key: 'name',
width: '20%'
},
{
title: '就诊医院',
dataIndex: 'orgName',
key: 'orgName',
width: '35%'
},
{
title: '居住地址',
dataIndex: 'addr',
key: 'addr',
width: '30%'
}
];
return (
<div className="list-page">
<ul className="table-header">
{columns.map((item) => (
<li style={{ width: item.width }} key={item.key}>
{item.title}
</li>
))}
</ul>
<div
onScrollCapture={onScrollCapture}
style={{ height: 320, overflowY: 'scroll' }}
ref={(c) => {
scrollRef = c;
}}
>
<Table
columns={columns}
dataSource={dataSource}
size="small"
pagination={false}
rowKey="idNo"
/>
{!isMore ? <div className="no-more">已经到底啦</div> : null}
</div>
</div>
);
};
export default ListPage;
需要注意两点:1、为了固定表头,直接控制样式隐藏掉了antd的表头自己手写;2、scrollTop会有小数点导致等式不成立,解决方案:四舍五入。