什麼是無限滾動以及它的必要性?
滾動是水平或垂直移動網頁上部分內容的使用者操作(在大多數情況下)。
就像您在閱讀本文時所做的那樣。
無限意味著當您向下捲動網頁時,新內容會自動載入。
好吧,但是為什麼每個人都應該實現它?
可發現性
讓我們想像一下您最喜歡的電子商務商店正在舉辦黑色星期五促銷活動。
您在探索頁面上找到了幾個產品,但當您滾動到網頁底部而不是更多產品時,您發現了一個按鈕,可將您帶到下一個產品列表。
您將能夠看到新產品(但前提是您注意到該操作按鈕)。
無限滾動只是幫助用戶找到更多他們可能錯過的內容。
執行
為了實現無限滾動,我們需要檢查使用者是否到達頁面底部或容器。
但是偵測滾動的位置是非常昂貴的,並且由於不同的瀏覽器和設備,其位置值不可靠。
所以一個方法是觀看頁面的最後內容(元素)及其與視窗或容器的交點。
我們如何找到交點?
路口觀察者
它是一個 Web API,允許觀察內容或清單末尾的元素。
當這個元素(「哨兵」)變得可見(與視窗相交時,它會觸發回調函數。
透過這個函數我們可以取得更多資料並將其載入到網頁中。
整個觀察是異步發生的,這最小化對主執行緒的影響。
為了在 Reactjs 中實作 Intersection Observer,我們將以社群動態為例,我們將在貼文清單上進行無限滾動。
看一下這個組件,您就可以了解下面每個部分的詳細情況。
import { useEffect, useRef, useState } from "react"; interface IIntersectionObserverProps {} const allItems = [ "https://picsum.photos/200", "https://picsum.photos/200", "https://picsum.photos/200", "https://picsum.photos/200", ]; const IntersectionObserverImplement: React.FunctionComponent = (props) => { const cardRefs = useRef([]); // Initialize as an empty array const containerRef = useRef<htmldivelement null>(null); const [listItems, setListItems] = useState(allItems); useEffect(() => { const options = { root: containerRef.current, rootMargin: "0px", threshold: 0.5, }; const observer = new IntersectionObserver((entries, observer) => { entries.forEach((entry) => { if (entry.isIntersecting) { setListItems((prevItems) => [ ...prevItems, "https://picsum.photos/200", ]); observer.unobserve(entry.target); // Stop observing the current element } }); }, options); // Observe the last card only const lastCard = cardRefs.current[listItems.length - 1]; if (lastCard) { observer.observe(lastCard); } return () => observer.disconnect(); // Clean up observer on unmount }, [listItems]); return ( <div classname="container" ref="{containerRef}"> {listItems.map((eachItem, index) => ( <div classname="card" ref="{(el)"> (cardRefs.current[index] = el)} // Assign refs correctly key={index} > <h5 id="Post-index">Post {index}</h5> <img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/173443591411756.jpg?x-oss-process=image/resize,p_40" class="lazy" style="max-width:90%"200"}' height='{"150"}' alt="Reactjs 教學:使用 Intersection Observer 進行無限滾動。" > </div> ))} </div> ); }; export default IntersectionObserverImplement; </htmldivelement>
目標是偵測提要清單中的最後一個貼文(稱為哨兵)何時與視窗相交。一旦發生這種情況,就會加載並顯示更多帖子。
一個。初始化狀態和引用
const cardRefs = useRef([]); // For storing references to each card const containerRef = useRef<htmldivelement null>(null); // Reference to the scrollable container const [listItems, setListItems] = useState(allItems); // State to hold the list of items </htmldivelement>
cardRefs 一個數組,用來追蹤表示清單中卡片的 DOM 元素。
containerRef 指的是可滾動容器。
listItems 儲存頁面上目前可見項目的陣列。
b.渲染清單並分配引用
return ( <div classname="container" ref="{containerRef}"> {listItems.map((eachItem, index) => ( <div classname="card" ref="{(el)"> (cardRefs.current[index] = el)} // Assign a ref to each card key={index} > <h5 id="Post-index">Post {index}</h5> <img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/173443591411756.jpg?x-oss-process=image/resize,p_40" class="lazy" style="max-width:90%"200"}' height='{"150"}' alt="Reactjs 教學:使用 Intersection Observer 進行無限滾動。" > </div> ))} </div> );
containerRef 標記將發生滾動的容器。
cardRefs 為清單中的每張卡片分配一個參考。這確保我們可以告訴觀察者要監視哪個元素(例如,最後一張卡片)。
映射 listItems 以呈現清單中的每個項目。
每個 div 都被設計成一張卡片,並且有一個唯一的 React 鍵。
c.觀察最後一個貼文(項目)。
import { useEffect, useRef, useState } from "react"; interface IIntersectionObserverProps {} const allItems = [ "https://picsum.photos/200", "https://picsum.photos/200", "https://picsum.photos/200", "https://picsum.photos/200", ]; const IntersectionObserverImplement: React.FunctionComponent = (props) => { const cardRefs = useRef([]); // Initialize as an empty array const containerRef = useRef<htmldivelement null>(null); const [listItems, setListItems] = useState(allItems); useEffect(() => { const options = { root: containerRef.current, rootMargin: "0px", threshold: 0.5, }; const observer = new IntersectionObserver((entries, observer) => { entries.forEach((entry) => { if (entry.isIntersecting) { setListItems((prevItems) => [ ...prevItems, "https://picsum.photos/200", ]); observer.unobserve(entry.target); // Stop observing the current element } }); }, options); // Observe the last card only const lastCard = cardRefs.current[listItems.length - 1]; if (lastCard) { observer.observe(lastCard); } return () => observer.disconnect(); // Clean up observer on unmount }, [listItems]); return ( <div classname="container" ref="{containerRef}"> {listItems.map((eachItem, index) => ( <div classname="card" ref="{(el)"> (cardRefs.current[index] = el)} // Assign refs correctly key={index} > <h5 id="Post-index">Post {index}</h5> <img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/173443591411756.jpg?x-oss-process=image/resize,p_40" class="lazy" style="max-width:90%"200"}' height='{"150"}' alt="Reactjs 教學:使用 Intersection Observer 進行無限滾動。" > </div> ))} </div> ); }; export default IntersectionObserverImplement; </htmldivelement>
選項物件
const cardRefs = useRef([]); // For storing references to each card const containerRef = useRef<htmldivelement null>(null); // Reference to the scrollable container const [listItems, setListItems] = useState(allItems); // State to hold the list of items </htmldivelement>
root 指定滾動容器。
containerRef.current 指的是包裹所有卡片的 div。
如果 root 為 null,則預設觀察視窗。
rootMargin:定義根周圍的額外邊距。
「0px」表示沒有多餘的空間。您可以使用「100px」之類的值來提前觸發觀察者(例如,當元素即將出現時)。
閾值:決定觀察者觸發時目標元素必須可見的程度。
0.5 表示當最後一張卡片的 50% 可見時觸發回調。
建立觀察者
return ( <div classname="container" ref="{containerRef}"> {listItems.map((eachItem, index) => ( <div classname="card" ref="{(el)"> (cardRefs.current[index] = el)} // Assign a ref to each card key={index} > <h5 id="Post-index">Post {index}</h5> <img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/173443591411756.jpg?x-oss-process=image/resize,p_40" class="lazy" style="max-width:90%"200"}' height='{"150"}' alt="Reactjs 教學:使用 Intersection Observer 進行無限滾動。" > </div> ))} </div> );
IntersectionObserver 接受回呼函數和先前定義的選項物件。
每當觀察到的元素滿足選項中指定的條件時,回呼就會運作。
entries 參數是觀察到的元素的陣列。每個條目都包含有關元素是否相交(可見)的資訊。
如果entry.isIntersecting為true,則表示最後一張卡片現在可見:
- 使用 setListItems 將新項目加入清單。
- 取消觀察目前元素(entry.target)以防止冗餘觸發器。
觀察最後一張牌
useEffect(() => { const options = { root: containerRef.current, rootMargin: "0px", threshold: 0.5, }; const observer = new IntersectionObserver((entries, observer) => { entries.forEach((entry) => { if (entry.isIntersecting) { setListItems((prevItems) => [ ...prevItems, "https://picsum.photos/200", ]); observer.unobserve(entry.target); // Stop observing the current element } }); }, options); // Observe each card const lastCard = cardRefs.current[listItems.length - 1]; if (lastCard) { observer.observe(lastCard); } return () => observer.disconnect(); // Clean up observer on unmount }, [listItems]);
cardRefs.current:追蹤對所有卡片的引用。
listItems.length - 1:標識清單中的最後一項。
如果lastCard存在,使用observer.observe(lastCard)開始觀察它。
觀察者會監聽這張卡片,並在它可見時觸發回調。
清理
const options = { root: containerRef.current, // Observe within the container rootMargin: "0px", // No margin around the root container threshold: 0.5, // Trigger when 50% of the element is visible };
observer.disconnect() 刪除此 useEffect 所建立的所有觀察者。
這確保了當元件卸載或重新渲染時,舊的觀察者被清理。
每個階段會發生什麼事?
1。使用者滾動
當使用者捲動時,最後一張卡片進入視圖
2。路口觀察者觸發器
當最後一張牌的50%可見時,觀察者的回檔
運行。
3。新增項目
回呼將新項目加入到清單中 (setListItems)。
4。重複
觀察者與舊的最後一張卡片斷開連接並附加到
新的最後一張卡。
這就是我們如何使用 Intersection Observer.
實現無限滾動希望這對您有幫助:)
謝謝。
以上是Reactjs 教學:使用 Intersection Observer 進行無限滾動。的詳細內容。更多資訊請關注PHP中文網其他相關文章!

選擇Python還是JavaScript應基於職業發展、學習曲線和生態系統:1)職業發展:Python適合數據科學和後端開發,JavaScript適合前端和全棧開發。 2)學習曲線:Python語法簡潔,適合初學者;JavaScript語法靈活。 3)生態系統:Python有豐富的科學計算庫,JavaScript有強大的前端框架。

JavaScript框架的強大之處在於簡化開發、提升用戶體驗和應用性能。選擇框架時應考慮:1.項目規模和復雜度,2.團隊經驗,3.生態系統和社區支持。

引言我知道你可能會覺得奇怪,JavaScript、C 和瀏覽器之間到底有什麼關係?它們之間看似毫無關聯,但實際上,它們在現代網絡開發中扮演著非常重要的角色。今天我們就來深入探討一下這三者之間的緊密聯繫。通過這篇文章,你將了解到JavaScript如何在瀏覽器中運行,C 在瀏覽器引擎中的作用,以及它們如何共同推動網頁的渲染和交互。 JavaScript與瀏覽器的關係我們都知道,JavaScript是前端開發的核心語言,它直接在瀏覽器中運行,讓網頁變得生動有趣。你是否曾經想過,為什麼JavaScr

Node.js擅長於高效I/O,這在很大程度上要歸功於流。 流媒體匯總處理數據,避免內存過載 - 大型文件,網絡任務和實時應用程序的理想。將流與打字稿的類型安全結合起來創建POWE

Python和JavaScript在性能和效率方面的差異主要體現在:1)Python作為解釋型語言,運行速度較慢,但開發效率高,適合快速原型開發;2)JavaScript在瀏覽器中受限於單線程,但在Node.js中可利用多線程和異步I/O提升性能,兩者在實際項目中各有優勢。

JavaScript起源於1995年,由布蘭登·艾克創造,實現語言為C語言。 1.C語言為JavaScript提供了高性能和系統級編程能力。 2.JavaScript的內存管理和性能優化依賴於C語言。 3.C語言的跨平台特性幫助JavaScript在不同操作系統上高效運行。

JavaScript在瀏覽器和Node.js環境中運行,依賴JavaScript引擎解析和執行代碼。 1)解析階段生成抽象語法樹(AST);2)編譯階段將AST轉換為字節碼或機器碼;3)執行階段執行編譯後的代碼。

Python和JavaScript的未來趨勢包括:1.Python將鞏固在科學計算和AI領域的地位,2.JavaScript將推動Web技術發展,3.跨平台開發將成為熱門,4.性能優化將是重點。兩者都將繼續在各自領域擴展應用場景,並在性能上有更多突破。


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

SAP NetWeaver Server Adapter for Eclipse
將Eclipse與SAP NetWeaver應用伺服器整合。

Atom編輯器mac版下載
最受歡迎的的開源編輯器

MantisBT
Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

SublimeText3 Linux新版
SublimeText3 Linux最新版

ZendStudio 13.5.1 Mac
強大的PHP整合開發環境