VirtualList 虚拟列表
只渲染可视窗口内的项,支持定高与动态高度两种模式(动态模式按预计算偏移 + 二分查找定位窗口)。
基础用法
定高 / 动态高度 / overscan
定高
#0 · 项目 1
#1 · 项目 2
#2 · 项目 3
#3 · 项目 4
动态高度
#0 · 项目 1
#1 · 项目 2
#2 · 项目 3
预渲染缓冲(overscan)
#0 · 项目 1
#1 · 项目 2
#2 · 项目 3
#3 · 项目 4
#4 · 项目 5
#5 · 项目 6
#6 · 项目 7
#7 · 项目 8
#8 · 项目 9
#9 · 项目 10
#10 · 项目 11
#11 · 项目 12
#12 · 项目 13
#13 · 项目 14
#14 · 项目 15
#15 · 项目 16
import { LhVirtualList } from '@lh-ui/react'
const listData = Array.from({ length: 1000 }, (_, i) => `项目 ${i + 1}`)
const dynamicSize = (index: number) => (index % 3 === 0 ? 56 : 36)
export default function Demo() {
return (
<div className="demo-col">
{/* 定高:itemHeight 与行内容高度一致(height + padding 双设时用 border-box) */}
<LhVirtualList
data={listData}
height={200}
itemHeight={40}
renderItem={(item, index) => (
<div
style={{
height: '100%',
boxSizing: 'border-box',
display: 'flex',
alignItems: 'center',
padding: '0 12px',
}}
>
{`#${index}`} · {item}
</div>
)}
/>
{/* 动态高度:itemSize 返回每项高度(可基于测量结果动态返回) */}
<LhVirtualList
data={listData}
height={200}
itemSize={dynamicSize}
renderItem={(item, index) => (
<div
style={{
height: `${dynamicSize(index)}px`,
padding: '10px 12px',
boxSizing: 'border-box',
}}
>
{`#${index}`} · {item}
</div>
)}
/>
{/* overscan:窗口外上下各多渲染 8 行,减少快速滚动时的白屏 */}
<LhVirtualList
data={listData}
height={200}
itemHeight={40}
overscan={8}
renderItem={(item, index) => (
<div
style={{
height: '100%',
boxSizing: 'border-box',
display: 'flex',
alignItems: 'center',
padding: '0 12px',
}}
>
{`#${index}`} · {item}
</div>
)}
/>
</div>
)
}
VirtualList Props
| 属性 | 说明 | 类型 | 可选值 | 默认值 |
|---|---|---|---|---|
| data | 数据源 | T[] | — | — |
| height | 容器高度(数字为 px) | number | string | — | — |
| itemHeight | 定高模式的项高(与 itemSize 二选一) | number | — | — |
| itemSize | 动态高度模式:返回每项高度的函数 | (index: number) => number | — | — |
| renderItem | 项渲染函数(作用域参数 { item, index }) | (item: T, index: number) => ReactNode | — | — |
| overscan | 过扫描项数(窗口外上下各多渲染的行数) | number | — | 2 |
| sx | 快速布局属性 | SxProps | — | — |
与 Vue 版的对应
data / height / itemHeight / itemSize / overscan 与 lh-ui-plus 的 LhVirtualList
同名同义;React 无插槽,plus 的 #default 作用域插槽({ item, index })合并为 renderItem
渲染函数(与 Tree 的 renderNode / Table 列 render 同惯例)。
两种模式
提供 itemSize 时走动态高度模式(core 预计算偏移 + 二分查找定位窗口);否则按定高
itemHeight(缺省按 40px 估算)直接计算区间。行内容高度请与计量保持一致——
height 与 padding 双设时用 box-sizing: border-box,避免实际行高与窗口计算错位。
无障碍
容器 overflow: auto 可键盘滚动;窗口外的项不在 DOM 中,屏读按需获取(长列表的固有取舍,
建议配合搜索 / 筛选缩小范围)。若需完整语义表格请用 Table(其虚拟滚动同样由 core 纯函数驱动)。
样式
import '@lh-ui/react/style/virtual-list'