網站首頁 編程語言 正文
簡介
提供虛擬化列表能力的 Hook,用于解決展示海量數據渲染時首屏渲染緩慢和滾動卡頓問題。
詳情可見官網,文章源代碼可以點擊這里。
實現原理
其實現原理監聽外部容器的 scroll 事件以及其 size 發生變化的時候,觸發計算邏輯算出內部容器的高度和 marginTop 值。
具體實現
其監聽滾動邏輯如下:
// 當外部容器的 size 發生變化的時候,觸發計算邏輯
useEffect(() => {
if (!size?.width || !size?.height) {
return;
}
// 重新計算邏輯
calculateRange();
}, [size?.width, size?.height, list]);
// 監聽外部容器的 scroll 事件
useEventListener(
'scroll',
e => {
// 如果是直接跳轉,則不需要重新計算
if (scrollTriggerByScrollToFunc.current) {
scrollTriggerByScrollToFunc.current = false;
return;
}
e.preventDefault();
// 計算
calculateRange();
},
{
// 外部容器
target: containerTarget,
},
);
其中 calculateRange 非常重要,它基本實現了虛擬滾動的主流程邏輯,其主要做了以下的事情:
- 獲取到整個內部容器的高度 totalHeight。
- 根據外部容器的 scrollTop 算出已經“滾過”多少項,值為 offset。
- 根據外部容器高度以及當前的開始索引,獲取到外部容器能承載的個數 visibleCount。
- 并根據 overscan(視區上、下額外展示的 DOM 節點數量)計算出開始索引(start)和(end)。
- 根據開始索引獲取到其距離最開始的距離(offsetTop)。
- 最后根據 offsetTop 和 totalHeight 設置內部容器的高度和 marginTop 值。
變量很多,可以結合下圖,會比較清晰理解:
代碼如下:
// 計算范圍,由哪個開始,哪個結束
const calculateRange = () => {
// 獲取外部和內部容器
// 外部容器
const container = getTargetElement(containerTarget);
// 內部容器
const wrapper = getTargetElement(wrapperTarget);
if (container && wrapper) {
const {
// 滾動距離頂部的距離。設置或獲取位于對象最頂端和窗口中可見內容的最頂端之間的距離
scrollTop,
// 內容可視區域的高度
clientHeight,
} = container;
// 根據外部容器的 scrollTop 算出已經“滾過”多少項
const offset = getOffset(scrollTop);
// 可視區域的 DOM 個數
const visibleCount = getVisibleCount(clientHeight, offset);
// 開始的下標
const start = Math.max(0, offset - overscan);
// 結束的下標
const end = Math.min(list.length, offset + visibleCount + overscan);
// 獲取上方高度
const offsetTop = getDistanceTop(start);
// 設置內部容器的高度,總的高度 - 上方高度
// @ts-ignore
wrapper.style.height = totalHeight - offsetTop + 'px';
// margin top 為上方高度
// @ts-ignore
wrapper.style.marginTop = offsetTop + 'px';
// 設置最后顯示的 List
setTargetList(
list.slice(start, end).map((ele, index) => ({
data: ele,
index: index + start,
})),
);
}
};
其它就是這個函數的輔助函數了,包括:
- 根據外部容器以及內部每一項的高度,計算出可視區域內的數量:
// 根據外部容器以及內部每一項的高度,計算出可視區域內的數量
const getVisibleCount = (containerHeight: number, fromIndex: number) => {
// 知道每一行的高度 - number 類型,則根據容器計算
if (isNumber(itemHeightRef.current)) {
return Math.ceil(containerHeight / itemHeightRef.current);
}
// 動態指定每個元素的高度情況
let sum = 0;
let endIndex = 0;
for (let i = fromIndex; i < list.length; i++) {
// 計算每一個 Item 的高度
const height = itemHeightRef.current(i, list[i]);
sum += height;
endIndex = i;
// 大于容器寬度的時候,停止
if (sum >= containerHeight) {
break;
}
}
// 最后一個的下標減去開始一個的下標
return endIndex - fromIndex;
};
- 根據 scrollTop 計算上面有多少個 DOM 節點:
// 根據 scrollTop 計算上面有多少個 DOM 節點
const getOffset = (scrollTop: number) => {
// 每一項固定高度
if (isNumber(itemHeightRef.current)) {
return Math.floor(scrollTop / itemHeightRef.current) + 1;
}
// 動態指定每個元素的高度情況
let sum = 0;
let offset = 0;
// 從 0 開始
for (let i = 0; i < list.length; i++) {
const height = itemHeightRef.current(i, list[i]);
sum += height;
if (sum >= scrollTop) {
offset = i;
break;
}
}
// 滿足要求的最后一個 + 1
return offset + 1;
};
- 獲取上部高度:
// 獲取上部高度
const getDistanceTop = (index: number) => {
// 每一項高度相同
if (isNumber(itemHeightRef.current)) {
const height = index * itemHeightRef.current;
return height;
}
// 動態指定每個元素的高度情況,則 itemHeightRef.current 為函數
const height = list
.slice(0, index)
// reduce 計算總和
// @ts-ignore
.reduce((sum, _, i) => sum + itemHeightRef.current(i, list[index]), 0);
return height;
};
- 計算總的高度:
// 計算總的高度
const totalHeight = useMemo(() => {
// 每一項高度相同
if (isNumber(itemHeightRef.current)) {
return list.length * itemHeightRef.current;
}
// 動態指定每個元素的高度情況
// @ts-ignore
return list.reduce(
(sum, _, index) => sum + itemHeightRef.current(index, list[index]),
0,
);
}, [list]);
最后暴露一個滾動到指定的 index 的函數,其主要是計算出該 index 距離頂部的高度 scrollTop,設置給外部容器。并觸發 calculateRange 函數。
// 滾動到指定的 index
const scrollTo = (index: number) => {
const container = getTargetElement(containerTarget);
if (container) {
scrollTriggerByScrollToFunc.current = true;
// 滾動
container.scrollTop = getDistanceTop(index);
calculateRange();
}
};
思考總結
對于高度相對比較確定的情況,我們做虛擬滾動還是相對簡單的,但假如高度不確定呢?
或者換另外一個角度,當我們的滾動不是縱向的時候,而是橫向,該如何處理呢?
原文鏈接:https://segmentfault.com/a/1190000042447474
相關推薦
- 2022-04-20 Flutter如何輕松實現動態更新ListView淺析_Android
- 2022-08-03 GoFrame?glist?基礎使用和自定義遍歷_Golang
- 2022-04-21 Docker - Error: Error response from daemon: No com
- 2022-11-09 SQL語句過濾條件放在on與where子句中的區別和聯系淺析_MsSql
- 2022-03-26 R語言基于Keras的MLP神經網絡及環境搭建_R語言
- 2024-01-09 idea如何設置自動換行
- 2022-11-19 Linux下定時自動備份Docker中所有SqlServer數據庫的腳本_docker
- 2022-06-12 如何在React項目中使用AntDesign_React
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支