import React from 'react';
import { Table } from 'antd';
/**
* 以下是个简单的例子
*/
export default class App extends React.Component {
componentDidMount() {
// 滚动监听
window.addEventListener('scroll', this.getScrollTop, true);
}
componentWillUnmount() {
// 关闭滚动监听
window.removeEventListener('scroll', this.getScrollTop, true);
}
/**
* list-table-wrapper为滚动区域, 通过改变table距list-table-wrapper的marginTop(也可以通过绝对定位设置top),实现虚拟滚动的效果
*/
getScrollTop = () => {
const { dataList, containerHeight } = this.props;
let startIndex = 0;
const dataLength = dataList.length;
// 表格每一行的高
const rowHeight = 70;
// 屏幕最多展示几行(屏幕高除以行高)
this.visibleNum = Math.floor(containerHeight / rowHeight);
const scrollElement = document.getElementById('list-table-wrapper');
// 滚动据顶部的距离
const scrollY = scrollElement.getBoundingClientRect().top;
// 最大的序号
const maxIndex = dataLength - this.visibleNum;
// 列表展示数据的开始序号
startIndex = Math.min(maxIndex, Math.ceil(scrollY / rowHeight));
// 可滚动的高度(表格展示总数据时的高度)
const scrollHeight = `${rowHeight * dataLength}px`;
scrollElement.style.height = scrollHeight;
const tableElement = document.getElementById('ant-table-wrapper');
// 不超出最大限制才更改marginTop
if (startIndex <= maxIndex) {
tableElement.style.marginTop = startIndex === 0 ? '0' : `${startIndex * rowHeight}px`;
}
}
this.setState({ startIndex });
};
render() {
const { dataList } = this.props;
// 仅渲染可视区域展现的数据
const currentList = dataList.slice(startIndex, startIndex + this.visibleNum);
return (
<div id="list-table-wrapper">
<Table
id="ant-table-wrapper"
rowKey="id"
dataSource={currentList}
rowSelection={{
columnTitle: ' ', // 可隐藏表格头部的复选框
}}
/>
</div>
);
}
}
超简单实现antd3的table组件虚拟滚动
最新推荐文章于 2025-04-03 12:32:28 发布