实际业务中,列表项高度往往是动态的
实际业务中,列表项高度往往是动态的(如内容自适应、图片加载)。定高方案会失效,需要更复杂的实现。
3.1 问题分析
无法直接通过 scrollTop / itemHeight 计算索引
需要维护每个 item 的真实高度缓存
滚动位置与索引的映射需要二分查找优化
3.2 实现方案
// 优化:只计算到当前可视区域 + 缓冲区的 top 值
// 使用惰性计算 + 缓存策略
const getItemMeta = (index: number): ItemMeta => {
const cached = measuredCache.get(index);
if (cached) return cached;
// 向前查找最近已计算的项
let nearestIndex = index - 1;
while (nearestIndex >= 0 && !measuredCache.has(nearestIndex)) {
nearestIndex--;
}
let top = nearestIndex >= 0
? measuredCache.get(nearestIndex)!.bottom
: 0;
// 计算从 nearestIndex+1 到 index 的所有项
for (let i = nearestIndex + 1; i <= index; i++) {
const h = measuredCache.get(i)?.height ?? estimatedItemHeight;
const meta = {
index: i,
height: h,
top,
bottom: top + h
};
measuredCache.set(i, meta);
top += h;
}
return measuredCache.get(index)!;
};

浙公网安备 33010602011771号