react-window 是一个轻量级的虚拟列表库,适用于大多数虚拟列表需求。它提供了简单易用的 API 和良好的性能。
npm install react-window
import React, { useCallback } from 'react';
import { FixedSizeList as List } from 'react-window';
const generateUniqueKey = () => `${new Date().getTime()}-${Math.random().toString(36).substr(2, 9)}`;
const DATA_LIST = Array.from({ length: 100000 }, (_, index) => ({
key: generateUniqueKey(),
slogan: `Item ${index + 1}`,
bgColor: `hsl(${Math.random() * 360}, 100%, 75%)`
}));
const ITEM_HEIGHT = 35;
const Row = ({ index, style }) => (
<div style={{ ...style, backgroundColor: DATA_LIST[index].bgColor }}>
{DATA_LIST[index].slogan}
</div>
);
const VirtualListPage = () => (
<List
height={window.innerHeight}
itemCount={DATA_LIST.length}
itemSize={ITEM_HEIGHT}
width={'100%'}
>
{Row}
</List>
);
export default VirtualListPage;
react-virtualized 是一个功能强大的虚拟列表库,提供了更多的功能和配置选项,适用于复杂的虚拟列表需求。
npm install react-virtualized
import React from 'react';
import { List } from 'react-virtualized';
const generateUniqueKey = () => `${new Date().getTime()}-${Math.random().toString(36).substr(2, 9)}`;
const DATA_LIST = Array.from({ length: 100000 }, (_, index) => ({
key: generateUniqueKey(),
slogan: `Item ${index + 1}`,
bgColor: `hsl(${Math.random() * 360}, 100%, 75%)`
}));
const ITEM_HEIGHT = 35;
const rowRenderer = ({ key, index, style }) => (
<div key={key} style={{ ...style, backgroundColor: DATA_LIST[index].bgColor }}>
{DATA_LIST[index].slogan}
</div>
);
const VirtualListPage = () => (
<List
width={window.innerWidth}
height={window.innerHeight}
rowCount={DATA_LIST.length}
rowHeight={ITEM_HEIGHT}
rowRenderer={rowRenderer}
/>
);
export default VirtualListPage;
react-virtual 是一个现代的虚拟列表库,提供了简单的 API 和良好的性能。
npm install @tanstack/react-virtual
import React from 'react';
import { useVirtual } from '@tanstack/react-virtual';
const generateUniqueKey = () => `${new Date().getTime()}-${Math.random().toString(36).substr(2, 9)}`;
const DATA_LIST = Array.from({ length: 100000 }, (_, index) => ({
key: generateUniqueKey(),
slogan: `Item ${index + 1}`,
bgColor: `hsl(${Math.random() * 360}, 100%, 75%)`
}));
const ITEM_HEIGHT = 35;
const VirtualListPage = () => {
const parentRef = React.useRef();
const rowVirtualizer = useVirtual({
size: DATA_LIST.length,
parentRef,
estimateSize: React.useCallback(() => ITEM_HEIGHT, []),
});
return (
<div
ref={parentRef}
style={{
height: '100vh',
width: '100%',
overflow: 'auto',
}}
>
<div
style={{
height: `${rowVirtualizer.totalSize}px`,
width: '100%',
position: 'relative',
}}
>
{rowVirtualizer.virtualItems.map(virtualRow => (
<div
key={virtualRow.index}
ref={virtualRow.measureRef}
style={{
position: 'absolute',
top: 0,
left: 0,
width: '100%',
height: `${ITEM_HEIGHT}px`,
transform: `translateY(${virtualRow.start}px)`,
backgroundColor: DATA_LIST[virtualRow.index].bgColor,
}}
>
{DATA_LIST[virtualRow.index].slogan}
</div>
))}
</div>
</div>
);
};
export default VirtualListPage;
antd
库:优秀的 React 库,这里不多介绍,详情看官网。antd
库:优秀的 React 库,不多介绍。