@bowenhuang/react-virtual-list
v0.1.0
Published
A lightweight virtual list component for React with dynamic item heights.
Downloads
94
Maintainers
Readme
react-virtual-list
一个轻量级 React 虚拟列表组件,支持动态高度列表渲染。
安装
npm install react-virtual-list本地开发
# 运行单元测试
npm run test
# 启动 demo 页面
npm run demo快速开始
import React from 'react';
import VirtualList from 'react-virtual-list';
type Row = { id: string; title: string };
const data: Row[] = Array.from({ length: 2000 }).map((_, i) => ({
id: String(i),
title: `Row ${i}`,
}));
export default function Demo() {
return (
<VirtualList
data={data}
estimatedItemHeight={56}
overscan={600}
getItemKey={(item) => item.id}
itemContent={(index, item) => (
<div style={{ padding: '16px', borderBottom: '1px solid #eee' }}>
{index}. {item.title}
</div>
)}
/>
);
}动态高度示例
import React from 'react';
import VirtualList from 'react-virtual-list';
const blocks = Array.from({ length: 500 }).map((_, i) => ({
id: i,
text: `Block ${i} ` + 'content '.repeat((i % 6) + 1),
}));
export default function DynamicDemo() {
return (
<VirtualList
data={blocks}
estimatedItemHeight={120}
itemContent={(_, item) => (
<article style={{ padding: 12 }}>
<h4>{item.id}</h4>
<p>{item.text}</p>
</article>
)}
/>
);
}API
VirtualListProps<T>
| 属性 | 类型 | 默认值 | 说明 |
| --- | --- | --- | --- |
| data | T[] | - | 完整列表数据源 |
| itemContent | (index: number, item: T) => ReactNode | - | 单项渲染函数 |
| customScrollParent | HTMLElement \| null | document.documentElement | 自定义滚动容器 |
| estimatedItemHeight | number | 200 | 未测量前的预估行高 |
| overscan | number | 800 | 视区上下额外渲染像素(px) |
| className | string | - | 外层容器类名 |
| style | CSSProperties | - | 外层容器样式 |
| itemClassName | (item: T, index: number) => string | - | 单项容器类名回调 |
| getItemKey | (item: T, index: number) => React.Key | index | 列表项稳定 key 生成器 |
| components.Item | ComponentType<VirtualListItemComponentProps<T>> | - | 可选自定义 Item 包装组件 |
VirtualListItemComponentProps<T>
| 字段 | 类型 | 说明 |
| --- | --- | --- |
| item | T | 当前项数据 |
| index | number | 当前项索引 |
| className | string \| undefined | 来自 itemClassName 的类名 |
| children | ReactNode | itemContent 渲染结果 |
说明
- 该包面向浏览器环境(对 SSR 场景做了
window/document安全判断)。 - 建议优先传入稳定的
getItemKey以获得更好的渲染性能。 - 动态高度会在渲染后测量,测量前使用
estimatedItemHeight参与计算。
