虚拟列表
按需显示的一种实现,只对可见区域(视口 View port)进行渲染,对非可见区域中的数据不渲染或部分渲染(作为 Buffer)的技术。目的是达到极高的渲染性能,提升用户体验。
原理
模型
虚拟列表分为
- VirtualList 虚拟列表区域
- VisibleRange 视口区域
- RenderRange(PreScanRange + VisibleRange + PostScanRange) 渲染区域
- RenderRange = PreScanRange + VisibleRange + PostScanRange = stop - start
- LoadedRange 已加载区域
- LoadedRange = lastMeasureIndex
- UnloadedRange 未加载区域
- UnloadedRange = VisibleRange.size - lastMeasureIndex
实际滚动过程中需要不断更新 start、stop、lastMeasureIndex,从而得出渲染区域和视口区域
位置缓存
LoadedRange 中的元素已经得到计算的尺寸、偏移缓存哈希中,用以减少重复计算,以提高性能。
查找指定元素
基于有序元素偏移列表
- LoadedRange 中使用二分查找算法,时间复杂度可降低到 O(lgN);
- UnloadedRange 中使用指数查找算法,时间复杂度同样为 O(lgN), 但可以将 N 值缩小,进一步提高搜索性能
先用指数搜索定位范围 low - heigh,内嵌二分查找 target
滚动偏移计算
VirtualList 总长度
TotalSize = lastMeasuredSizeAndPosition.offset + lastMeasuredSizeAndPosition.size + ( itemCount - lastMeasuredIndex - 1 ) * estimatedItemSize
使用已经计算的偏移尺寸,加上未加载的预估尺寸,即基本等价于整体尺寸
不定尺寸子元素
- 静态计算;提前预知所有元素的尺寸,并通过数组类型的 prop 传入,每个列表项的高度通过索引来获得
- 动态延迟计算:传入获取列表项高度的方法,给这个方法传入 item 和 index,返回对应列表项的高度
将上面的方式得出尺寸作为计算依据,若无法获取对应尺寸,则使用预估尺寸。
React-virtual
Auto-sizing, buttery smooth, headless virtualization… with just one hook.
https://react-virtual.tanstack.com/docs/api
import React from 'react'
import ReactDOM from 'react-dom'
import './index.css'
import { useVirtual } from 'react-virtual'
function App() {
const rows = new Array(10000)
.fill(true)
.map(() => 25 + Math.round(Math.random() * 100))
const columns = new Array(10000)
.fill(true)
.map(() => 75 + Math.round(Math.random() * 100))
return (
<div>
<p>
These components are using <strong>dynamic</strong> sizes. This means
that each element's exact dimensions are unknown when rendered. An
estimated dimension is used to get an a initial measurement, then this
measurement is readjusted on the fly as each element is rendered.
</p>
<br />
<br />
<h3>Rows</h3>
<RowVirtualizerDynamic rows={rows} columns={columns} />
<br />
<br />
<h3>Columns</h3>
<ColumnVirtualizerDynamic rows={rows} columns={columns} />
<br />
<br />
<h3>Grid</h3>
<GridVirtualizerDynamic rows={rows} columns={columns} />
</div>
)
}
function RowVirtualizerDynamic({ rows }) {
const parentRef = React.useRef()
const rowVirtualizer = useVirtual({
size: rows.length,
parentRef,
})
return (
<>
<div
ref={parentRef}
className="List"
style={{
height: `200px`,
width: `400px`,
overflow: 'auto',
}}
>
<div
style={{
height: rowVirtualizer.totalSize,
width: '100%',
position: 'relative',
}}
>
{rowVirtualizer.virtualItems.map(virtualRow => (
<div
key={virtualRow.index}
ref={virtualRow.measureRef}
className={virtualRow.index % 2 ? 'ListItemOdd' : 'ListItemEven'}
style={{
position: 'absolute',
top: 0,
left: 0,
width: '100%',
transform: `translateY(${virtualRow.start}px)`,
}}
>
<div style={{ height: rows[virtualRow.index] }}>
Row {virtualRow.index}
</div>
</div>
))}
</div>
</div>
</>
)
}
function ColumnVirtualizerDynamic({ columns }) {
const parentRef = React.useRef()
const columnVirtualizer = useVirtual({
horizontal: true,
size: columns.length,
parentRef,
})
return (
<>
<div
ref={parentRef}
className="List"
style={{
width: `400px`,
height: `100px`,
overflow: 'auto',
}}
>
<div
style={{
width: columnVirtualizer.totalSize,
height: '100%',
position: 'relative',
}}
>
{columnVirtualizer.virtualItems.map(virtualColumn => (
<div
key={virtualColumn.key}
ref={virtualColumn.measureRef}
className={
virtualColumn.index % 2 ? 'ListItemOdd' : 'ListItemEven'
}
style={{
position: 'absolute',
top: 0,
left: 0,
height: '100%',
transform: `translateX(${virtualColumn.start}px)`,
}}
>
<div style={{ width: columns[virtualColumn.index] }}>
Column {virtualColumn.index}
</div>
</div>
))}
</div>
</div>
</>
)
}
function GridVirtualizerDynamic({ rows, columns }) {
const parentRef = React.useRef()
const rowVirtualizer = useVirtual({
size: rows.length,
parentRef,
})
const columnVirtualizer = useVirtual({
horizontal: true,
size: columns.length,
parentRef,
})
const [show, setShow] = React.useState(true)
const halfWay = Math.floor(rows.length / 2)
return (
<>
<button onClick={() => setShow(old => !old)}>Toggle</button>
<button onClick={() => rowVirtualizer.scrollToIndex(halfWay)}>
Scroll to index {halfWay}
</button>
<button onClick={() => rowVirtualizer.scrollToIndex(rows.length - 1)}>
Scroll to index {rows.length - 1}
</button>
{show ? (
<div
ref={parentRef}
className="List"
style={{
height: `400px`,
width: `500px`,
overflow: 'auto',
}}
>
<div
style={{
height: rowVirtualizer.totalSize,
width: columnVirtualizer.totalSize,
position: 'relative',
}}
>
{rowVirtualizer.virtualItems.map(virtualRow => (
<React.Fragment key={virtualRow.key}>
{columnVirtualizer.virtualItems.map(virtualColumn => (
<div
key={virtualColumn.key}
ref={el => {
virtualRow.measureRef(el)
virtualColumn.measureRef(el)
}}
className={
virtualColumn.index % 2
? virtualRow.index % 2 === 0
? 'ListItemOdd'
: 'ListItemEven'
: virtualRow.index % 2
? 'ListItemOdd'
: 'ListItemEven'
}
style={{
position: 'absolute',
top: 0,
left: 0,
transform: `translateX(${virtualColumn.start}px) translateY(${virtualRow.start}px)`,
}}
>
<div
style={{
height: rows[virtualRow.index],
width: columns[virtualColumn.index],
}}
>
Cell {virtualRow.index}, {virtualColumn.index}
</div>
</div>
))}
</React.Fragment>
))}
</div>
</div>
) : null}
<br />
<br />
{process.env.NODE_ENV === 'development' ? (
<p>
<strong>Notice:</strong> You are currently running React in
development mode. Rendering performance will be slightly degraded
until this application is build for production.
</p>
) : null}
</>
)
}
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
)