React虛擬渲染實(shí)現(xiàn)50個或者一百個圖表渲染
前言
最近有個需求,一個頁面上要渲染50個或者100個圖表,把功能實(shí)現(xiàn)后,頁面太卡了。之前用過虛擬渲染能解決此類的問題,但用的都是別人寫好的庫,想了想,自己實(shí)現(xiàn)也并不復(fù)雜,于是決定自己實(shí)現(xiàn)一下。
需求
每行渲染3個圖表,右上角的切換可以有50個,100個,或者更多。
方案
虛擬列表其實(shí)就是對可視區(qū)域做渲染。對不可見的內(nèi)容不渲染或者預(yù)渲染一部分,預(yù)渲染一部分,可以減少白屏的內(nèi)容
我們從上面的圖可以看到
- 可視區(qū)域就是我們能看到的內(nèi)容
- 真實(shí)列表的長度 整個元素內(nèi)容所占的高度
- 邊框?yàn)閷?shí)線的Item 真正渲染的內(nèi)容
- 預(yù)渲染內(nèi)容 為了防止白屏,提前渲染幾條數(shù)據(jù)
實(shí)現(xiàn)
假如現(xiàn)在有 90 條數(shù)據(jù),可以區(qū)域內(nèi)容只能顯示3條
實(shí)現(xiàn)虛擬渲染,有關(guān)鍵幾個變量我們說下。
- preload 預(yù)加載的條數(shù),指的是我們上邊圖的預(yù)渲染內(nèi)容
- itemHeight列表每一項(xiàng)的高度
- scrollTop 可視區(qū)滾動條的高度
- screenHeight 可視區(qū)域的高度
- visibleCount 可視區(qū)域可以看到的條數(shù)。
公式 Math.ceil(screenHeight / itemHeight);
start列表當(dāng)中開始的索引。
公式 start = Math.floor(((scrollTop + screenHeight) / itemHeight)) - preload;
注意:邊界的判斷
start = start < 0 ? 0 : start;
end 列表當(dāng)中結(jié)束的索引
公式 end = start + visibleCount + preload;
注意:邊界的判斷
end = end > data.length ? data.length : end;
VirtualScroll 組件實(shí)現(xiàn)
import React, { useRef, useState, useEffect } from 'react'; import { requestTimeout, cancelTimeout } from '../../utils/timer'; import styles from './index.less'; const VirtualScroll = ({ data, itemHeight, preload = 1, renderItem }) => { const [v, setUpdateValue] = useState(0); // 用來更新組件 const containerRef = useRef(null); const resetIsScrollingTimeoutId = useRef(null); /** * 可視區(qū)域滾動事件 * 防抖處理 */ const onScroll = (e) => { if (resetIsScrollingTimeoutId.current !== null) { cancelTimeout(resetIsScrollingTimeoutId.current); } resetIsScrollingTimeoutId.current = requestTimeout( () => { setUpdateValue(val => (val + 1)); }, 150 ); } useEffect(() => { if (containerRef.current) { setUpdateValue(val => (val + 1)); } }, [containerRef.current]) if (!containerRef.current) { return <div className={styles.container} ref={containerRef}></div>; } let start = 0; // 開始的索引 let end = 0; // 結(jié)束索引 // const screenHeight = 300; const { scrollTop, offsetHeight: screenHeight } = containerRef.current; const visibleCount = Math.ceil((screenHeight / itemHeight)); // 顯示的數(shù)量 start = Math.floor(((scrollTop + screenHeight) / itemHeight)) - preload; // 開始的索引 start = start < 0 ? 0 : start; // 判斷邊界 end = start + visibleCount + preload; // end = end > data.length ? data.length : end; // 判斷結(jié)束邊界 const visibleData = data.map((item, index) => { item.index = index; return item; }).slice(start, end); /** * ${data.length * itemHeight}px 容器的總高度 * ${ item.index * itemHeight}px 沒個元素的高度 */ return ( <div className={styles.container} ref={containerRef} onScroll={onScroll}> <div style={{ width: '100%', height: `${data.length * itemHeight}px`, }}> { visibleData?.map((item, index) => { return <div key={item.index} style={{ position: 'absolute', width: '100%', height: `${itemHeight}px`, top: `${ item.index * itemHeight}px`}}> {renderItem(item)} </div> }) } </div> </div> ); } export default VirtualScroll;
接著我們看下timer工具方法,主要是有個防抖操作參考 react-window
const now = () => Date.now(); export function cancelTimeout(timeoutID) { cancelAnimationFrame(timeoutID.id); } export function requestTimeout(callback, delay) { const start = now(); function tick() { if (now() - start >= delay) { callback.call(null); } else { timeoutID.id = requestAnimationFrame(tick); } } const timeoutID = { id: requestAnimationFrame(tick), }; return timeoutID; }
這里我們看到用了requestAnimationFrame.它告訴瀏覽器——你希望執(zhí)行一個動畫,并且要求瀏覽器在下次重繪之前調(diào)用指定的回調(diào)函數(shù)更新動畫。該方法需要傳入一個回調(diào)函數(shù)作為參數(shù),該回調(diào)函數(shù)會在瀏覽器下一次重繪之前執(zhí)行?;卣{(diào)函數(shù)執(zhí)行次數(shù)通常是每秒60次
使用
import React from 'react'; import { FullScreenBox, VirtualScroll } from '../../../components'; import { BarChart } from 'charts'; import { Row, Col, Select } from 'antd'; //造數(shù)據(jù) let eventRateData = []; for (let index = 0; index < 60; index++) { const d = [ { x: 'text', y: 3.0, itemType: null, count: 0 }, { x: 'asdasdzzzcv', y: 1.0, itemType: null, count: 0 }, ]; d.cacheIndex = index + 1; eventRateData.push(d) } // 對數(shù)據(jù)進(jìn)行分組,每組有3條chart數(shù)據(jù) function arrayGroup(arr, count = 3) { const arrResult = []; let begin = 0; let end = count; for (let i = 0; i < Math.ceil(arr.length / count); i++) { const splitArr = arr.slice(begin, end); arrResult.push(splitArr); begin = end; end = end + count; } return arrResult; } function Chart({ data }) { return <BarChart data={data} height={200} title alias={['數(shù)據(jù)集名稱', '引用次數(shù)']} /> } const EventView = props => { const [state, setState] = useImmer({ count: 20 }) let data = eventRateData.slice(0, state.count); data = arrayGroup(data, 3); const renderItem = (item) => { return <Row> { item.map(child => { return <Col span={8} style={{ height: '200px' }}> <Chart data={child} title alias={['數(shù)據(jù)集名稱', '引用次數(shù)']} /> </Col> }) } </Row> } return ( <VirtualScroll renderItem={renderItem} data={data} itemHeight={200} preload={3} > </VirtualScroll> ); } export default EventView;
通過以上內(nèi)容,我們實(shí)現(xiàn)了虛擬滾動。
結(jié)束語
我們實(shí)現(xiàn)了固定高度的虛擬滾動,如果元素內(nèi)容高度不固定,我們還需要動態(tài)獲取高度。這塊內(nèi)容后續(xù)我們也實(shí)現(xiàn)一下,更多關(guān)于React虛擬渲染的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
react實(shí)現(xiàn)可播放的進(jìn)度條
這篇文章主要為大家詳細(xì)介紹了react實(shí)現(xiàn)可播放的進(jìn)度條,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-03-03React路由跳轉(zhuǎn)的實(shí)現(xiàn)示例
在React中,可以使用多種方法進(jìn)行路由跳轉(zhuǎn),本文主要介紹了React路由跳轉(zhuǎn)的實(shí)現(xiàn)示例,具有一定的參考價(jià)值,感興趣的可以了解一下2023-12-12React使用useImperativeHandle自定義暴露給父組件的示例詳解
useImperativeHandle?是?React?提供的一個自定義?Hook,用于在函數(shù)組件中顯式地暴露給父組件特定實(shí)例的方法,本文將介紹?useImperativeHandle的基本用法、常見應(yīng)用場景,需要的可以參考下2024-03-03解決React報(bào)錯Unexpected default export of an
這篇文章主要為大家介紹了React報(bào)錯Unexpected default export of anonymous function解決方法,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-12-12淺談React中的元素、組件、實(shí)例和節(jié)點(diǎn)
這篇文章主要介紹了淺談React中的元素、組件、實(shí)例和節(jié)點(diǎn),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-02-02使用React+SpringBoot開發(fā)一個協(xié)同編輯的表格文檔實(shí)現(xiàn)步驟
隨著云計(jì)算和團(tuán)隊(duì)協(xié)作的興起,協(xié)同編輯成為了許多企業(yè)和組織中必不可少的需求,本文小編就將為大家介紹如何使用React+SpringBoot簡單的開發(fā)一個協(xié)同編輯的表格文檔,感興趣的朋友一起看看吧2023-11-11React中useCallback useMemo到底該怎么用
在React函數(shù)組件中,當(dāng)組件中的props發(fā)生變化時(shí),默認(rèn)情況下整個組件都會重新渲染。換句話說,如果組件中的任何值更新,整個組件將重新渲染,包括沒有更改values/props的函數(shù)/組件。在react中,我們可以通過memo,useMemo以及useCallback來防止子組件的rerender2023-02-02react循環(huán)數(shù)據(jù)(列表)的實(shí)現(xiàn)
這篇文章主要介紹了react循環(huán)數(shù)據(jù)的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-04-04