国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

首頁(yè) web前端 js教程 Reactjs 教學(xué):使用 Intersection Observer 進(jìn)行無(wú)限滾動(dòng)。

Reactjs 教學(xué):使用 Intersection Observer 進(jìn)行無(wú)限滾動(dòng)。

Dec 17, 2024 pm 07:45 PM

什麼是無(wú)限滾動(dòng)以及它的必要性?

滾動(dòng)是水平或垂直移動(dòng)網(wǎng)頁(yè)上部分內(nèi)容的使用者操作(在大多數(shù)情況下)。

就像您在閱讀本文時(shí)所做的那樣。

無(wú)限意味著當(dāng)您向下捲動(dòng)網(wǎng)頁(yè)時(shí),新內(nèi)容會(huì)自動(dòng)載入。

好吧,但是為什麼每個(gè)人都應(yīng)該實(shí)現(xiàn)它?

可發(fā)現(xiàn)性

讓我們想像一下您最喜歡的電子商務(wù)商店正在舉辦黑色星期五促銷(xiāo)活動(dòng)。

您在探索頁(yè)面上找到了幾個(gè)產(chǎn)品,但當(dāng)您滾動(dòng)到網(wǎng)頁(yè)底部而不是更多產(chǎn)品時(shí),您發(fā)現(xiàn)了一個(gè)按鈕,可將您帶到下一個(gè)產(chǎn)品列表。

您將能夠看到新產(chǎn)品(但前提是您注意到該操作按鈕)。

無(wú)限滾動(dòng)只是幫助用戶(hù)找到更多他們可能錯(cuò)過(guò)的內(nèi)容。

執(zhí)行

為了實(shí)現(xiàn)無(wú)限滾動(dòng),我們需要檢查使用者是否到達(dá)頁(yè)面底部或容器。

但是偵測(cè)滾動(dòng)的位置是非常昂貴的,並且由於不同的瀏覽器和設(shè)備,其位置值不可靠。

所以一個(gè)方法是觀看頁(yè)面的最後內(nèi)容(元素)及其與視窗或容器的交點(diǎn)。

我們?nèi)绾握业浇稽c(diǎn)?

路口觀察者

它是一個(gè) Web API,允許觀察內(nèi)容或清單末尾的元素。

當(dāng)這個(gè)元素(「哨兵」)變得可見(jiàn)(與視窗相交時(shí),它會(huì)觸發(fā)回調(diào)函數(shù)。

透過(guò)這個(gè)函數(shù)我們可以取得更多資料並將其載入到網(wǎng)頁(yè)中。

整個(gè)觀察是異步發(fā)生的,這最小化對(duì)主執(zhí)行緒的影響。


為了在 Reactjs 中實(shí)作 Intersection Observer,我們將以社群動(dòng)態(tài)為例,我們將在貼文清單上進(jìn)行無(wú)限滾動(dòng)。

看一下這個(gè)組件,您就可以了解下面每個(gè)部分的詳細(xì)情況。

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<
  IIntersectionObserverProps
> = (props) => {
  const cardRefs = useRef<(HTMLDivElement | null)[]>([]); // 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>Post {index}</h5>
          <img width={"200"} height={"150"} src={eachItem} />
        </div>
      ))}
    </div>
  );
};

export default IntersectionObserverImplement;

目標(biāo)是偵測(cè)提要清單中的最後一個(gè)貼文(稱(chēng)為哨兵)何時(shí)與視窗相交。一旦發(fā)生這種情況,就會(huì)加載並顯示更多帖子。


一個(gè)。初始化狀態(tài)和引用
const cardRefs = useRef<(HTMLDivElement | null)[]>([]); // 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

cardRefs 一個(gè)數(shù)組,用來(lái)追蹤表示清單中卡片的 DOM 元素。

containerRef 指的是可滾動(dòng)容器。

listItems 儲(chǔ)存頁(yè)面上目前可見(jiàn)項(xiàng)目的陣列。

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>Post {index}</h5>
        <img width={"200"} height={"150"} src={eachItem} />
      </div>
    ))}
  </div>
);

containerRef 標(biāo)記將發(fā)生滾動(dòng)的容器。

cardRefs 為清單中的每張卡片分配一個(gè)參考。這確保我們可以告訴觀察者要監(jiān)視哪個(gè)元素(例如,最後一張卡片)。

映射 listItems 以呈現(xiàn)清單中的每個(gè)項(xiàng)目。
每個(gè) div 都被設(shè)計(jì)成一張卡片,並且有一個(gè)唯一的 React 鍵。

c.觀察最後一個(gè)貼文(項(xiàng)目)。
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<
  IIntersectionObserverProps
> = (props) => {
  const cardRefs = useRef<(HTMLDivElement | null)[]>([]); // 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>Post {index}</h5>
          <img width={"200"} height={"150"} src={eachItem} />
        </div>
      ))}
    </div>
  );
};

export default IntersectionObserverImplement;

選項(xiàng)物件

const cardRefs = useRef<(HTMLDivElement | null)[]>([]); // 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

root 指定滾動(dòng)容器。

containerRef.current 指的是包裹所有卡片的 div。
如果 root 為 null,則預(yù)設(shè)觀察視窗。

rootMargin:定義根周?chē)念~外邊距。

「0px」表示沒(méi)有多餘的空間。您可以使用「100px」之類(lèi)的值來(lái)提前觸發(fā)觀察者(例如,當(dāng)元素即將出現(xiàn)時(shí))。

閾值:決定觀察者觸發(fā)時(shí)目標(biāo)元素必須可見(jiàn)的程度。

0.5 表示當(dāng)最後一張卡片的 50% 可見(jiàn)時(shí)觸發(fā)回調(diào)。

建立觀察者

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>Post {index}</h5>
        <img width={"200"} height={"150"} src={eachItem} />
      </div>
    ))}
  </div>
);

IntersectionObserver 接受回呼函數(shù)和先前定義的選項(xiàng)物件。

每當(dāng)觀察到的元素滿(mǎn)足選項(xiàng)中指定的條件時(shí),回呼就會(huì)運(yùn)作。

entries 參數(shù)是觀察到的元素的陣列。每個(gè)條目都包含有關(guān)元素是否相交(可見(jiàn))的資訊。

如果entry.isIntersecting為true,則表示最後一張卡片現(xiàn)在可見(jiàn):

  1. 使用 setListItems 將新項(xiàng)目加入清單。
  2. 取消觀察目前元素(entry.target)以防止冗餘觸發(fā)器。

觀察最後一張牌

 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:追蹤對(duì)所有卡片的引用。

listItems.length - 1:標(biāo)識(shí)清單中的最後一項(xiàng)。

如果lastCard存在,使用observer.observe(lastCard)開(kāi)始觀察它。

觀察者會(huì)監(jiān)聽(tīng)這張卡片,並在它可見(jiàn)時(shí)觸發(fā)回調(diào)。

清理

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 所建立的所有觀察者。

這確保了當(dāng)元件卸載或重新渲染時(shí),舊的觀察者被清理。


Reactjs Tutorial : Infinite scrolling with Intersection Observer.

每個(gè)階段會(huì)發(fā)生什麼事?

1。使用者滾動(dòng)

當(dāng)使用者捲動(dòng)時(shí),最後一張卡片進(jìn)入視圖

2。路口觀察者觸發(fā)器

當(dāng)最後一張牌的50%可見(jiàn)時(shí),觀察者的回檔
運(yùn)行。

3。新增項(xiàng)目

回呼將新項(xiàng)目加入到清單中 (setListItems)。

4。重複

觀察者與舊的最後一張卡片斷開(kāi)連接並附加到
新的最後一張卡。

Reactjs Tutorial : Infinite scrolling with Intersection Observer.

這就是我們?nèi)绾问褂?Intersection Observer.

實(shí)現(xiàn)無(wú)限滾動(dòng)

希望這對(duì)您有幫助:)

謝謝。

以上是Reactjs 教學(xué):使用 Intersection Observer 進(jìn)行無(wú)限滾動(dòng)。的詳細(xì)內(nèi)容。更多資訊請(qǐng)關(guān)注PHP中文網(wǎng)其他相關(guān)文章!

本網(wǎng)站聲明
本文內(nèi)容由網(wǎng)友自願(yuàn)投稿,版權(quán)歸原作者所有。本站不承擔(dān)相應(yīng)的法律責(zé)任。如發(fā)現(xiàn)涉嫌抄襲或侵權(quán)的內(nèi)容,請(qǐng)聯(lián)絡(luò)admin@php.cn

熱AI工具

Undress AI Tool

Undress AI Tool

免費(fèi)脫衣圖片

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅(qū)動(dòng)的應(yīng)用程序,用於創(chuàng)建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線(xiàn)上人工智慧工具。

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費(fèi)的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費(fèi)的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強(qiáng)大的PHP整合開(kāi)發(fā)環(huán)境

Dreamweaver CS6

Dreamweaver CS6

視覺(jué)化網(wǎng)頁(yè)開(kāi)發(fā)工具

SublimeText3 Mac版

SublimeText3 Mac版

神級(jí)程式碼編輯軟體(SublimeText3)

熱門(mén)話(huà)題

Java vs. JavaScript:清除混亂 Java vs. JavaScript:清除混亂 Jun 20, 2025 am 12:27 AM

Java和JavaScript是不同的編程語(yǔ)言,各自適用於不同的應(yīng)用場(chǎng)景。 Java用於大型企業(yè)和移動(dòng)應(yīng)用開(kāi)發(fā),而JavaScript主要用於網(wǎng)頁(yè)開(kāi)發(fā)。

JavaScript評(píng)論:簡(jiǎn)短說(shuō)明 JavaScript評(píng)論:簡(jiǎn)短說(shuō)明 Jun 19, 2025 am 12:40 AM

JavascriptconcommentsenceenceEncorenceEnterential gransimenting,reading and guidingCodeeXecution.1)單inecommentsareusedforquickexplanations.2)多l(xiāng)inecommentsexplaincomplexlogicorprovideDocumentation.3)

如何在JS中與日期和時(shí)間合作? 如何在JS中與日期和時(shí)間合作? Jul 01, 2025 am 01:27 AM

JavaScript中的日期和時(shí)間處理需注意以下幾點(diǎn):1.創(chuàng)建Date對(duì)像有多種方式,推薦使用ISO格式字符串以保證兼容性;2.獲取和設(shè)置時(shí)間信息可用get和set方法,注意月份從0開(kāi)始;3.手動(dòng)格式化日期需拼接字符串,也可使用第三方庫(kù);4.處理時(shí)區(qū)問(wèn)題建議使用支持時(shí)區(qū)的庫(kù),如Luxon。掌握這些要點(diǎn)能有效避免常見(jiàn)錯(cuò)誤。

JavaScript與Java:開(kāi)發(fā)人員的全面比較 JavaScript與Java:開(kāi)發(fā)人員的全面比較 Jun 20, 2025 am 12:21 AM

JavaScriptIspreferredforredforwebdevelverment,而Javaisbetterforlarge-ScalebackendsystystemsandSandAndRoidApps.1)JavascriptexcelcelsincreatingInteractiveWebexperienceswebexperienceswithitswithitsdynamicnnamicnnamicnnamicnnamicnemicnemicnemicnemicnemicnemicnemicnemicnddommanipulation.2)

為什麼要將標(biāo)籤放在的底部? 為什麼要將標(biāo)籤放在的底部? Jul 02, 2025 am 01:22 AM

PlacingtagsatthebottomofablogpostorwebpageservespracticalpurposesforSEO,userexperience,anddesign.1.IthelpswithSEObyallowingsearchenginestoaccesskeyword-relevanttagswithoutclutteringthemaincontent.2.Itimprovesuserexperiencebykeepingthefocusonthearticl

JavaScript:探索用於高效編碼的數(shù)據(jù)類(lèi)型 JavaScript:探索用於高效編碼的數(shù)據(jù)類(lèi)型 Jun 20, 2025 am 12:46 AM

javascripthassevenfundaMentalDatatypes:數(shù)字,弦,布爾值,未定義,null,object和symbol.1)numberSeadUble-eaduble-ecisionFormat,forwidevaluerangesbutbecautious.2)

什麼是在DOM中冒泡和捕獲的事件? 什麼是在DOM中冒泡和捕獲的事件? Jul 02, 2025 am 01:19 AM

事件捕獲和冒泡是DOM中事件傳播的兩個(gè)階段,捕獲是從頂層向下到目標(biāo)元素,冒泡是從目標(biāo)元素向上傳播到頂層。 1.事件捕獲通過(guò)addEventListener的useCapture參數(shù)設(shè)為true實(shí)現(xiàn);2.事件冒泡是默認(rèn)行為,useCapture設(shè)為false或省略;3.可使用event.stopPropagation()阻止事件傳播;4.冒泡支持事件委託,提高動(dòng)態(tài)內(nèi)容處理效率;5.捕獲可用於提前攔截事件,如日誌記錄或錯(cuò)誤處理。了解這兩個(gè)階段有助於精確控制JavaScript響應(yīng)用戶(hù)操作的時(shí)機(jī)和方式。

Java和JavaScript有什麼區(qū)別? Java和JavaScript有什麼區(qū)別? Jun 17, 2025 am 09:17 AM

Java和JavaScript是不同的編程語(yǔ)言。 1.Java是靜態(tài)類(lèi)型、編譯型語(yǔ)言,適用於企業(yè)應(yīng)用和大型系統(tǒng)。 2.JavaScript是動(dòng)態(tài)類(lèi)型、解釋型語(yǔ)言,主要用於網(wǎng)頁(yè)交互和前端開(kāi)發(fā)。

See all articles