模拟
2024年01月29日
一、认识
虚拟列表 分为可视区域和非可视区域。虚拟列表 只渲染可视区域列表项, 当滚动发生时, 通过计算获得可视区域内的列表项。架构如下所示:
Preview
1.1 相关变量
-
start
: 根据offset
、overscan
计算得出的可视区域开始索引 -
end
: 根据overscan
、offset
、visibleCount
计算出的可视区域结束索引 -
offset
: 根据containerTarget
的scrollTop
计算出已经滚动过多少项 -
visibleCount
: 根据containerTarget
的clientHeight
以及当前的开始索引, 获取到containerTarget
能够承载的个数 -
offsetTop
: 根据开始索引获取到其距离最开始的距离, 用于margin-top
偏移值 -
totalHeight
:wrapperTarget
容器高度
1.2 开始索引计算
const start = Math.max(0, offset - overscan);
1.3 结束索引计算
const end = Math.min(list.length, offset + visibleCount + overscan);
1.4 已经滚动项计算
if (isNumber(itemHeightRef.current)) {
return Math.floor(scrollTop / itemHeightRef.current) + 1;
}
let sum = 0;
let offset = 0;
for (let i = 0; i < list.length; i++) {
const height = itemHeightRef.current(i, list[i]);
sum += height;
if (sum >= scrollTop) {
offset = i;
break;
}
}
return offset + 1;