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

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

Reactjs 教程:使用 Intersection Observer 進(jìn)行無限滾動(dòng)。

Dec 17, 2024 pm 07:45 PM

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

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

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

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

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

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

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

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

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

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

執(zhí)行

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

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

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

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

路口觀察者

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

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

通過這個(gè)函數(shù)我們可以獲取更多數(shù)據(jù)并將其加載到網(wǎng)頁中。

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


為了在 Reactjs 中實(shí)現(xiàn) Intersection Observer,我們將以社交提要為例,我們將在帖子列表上進(jìn)行無限滾動(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è)帖子(稱為哨兵)何時(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ù)組,用于跟蹤表示列表中卡片的 DOM 元素。

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

listItems 保存頁面上當(dāng)前可見項(xiàng)目的數(shù)組。

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)對(duì)象

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,則默認(rèn)觀察視口。

rootMargin:定義根周圍的額外邊距。

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

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

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

創(chuàng)建觀察者

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 接受回調(diào)函數(shù)和之前定義的選項(xiàng)對(duì)象。

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

entries 參數(shù)是觀察到的元素的數(shù)組。每個(gè)條目都包含有關(guān)元素是否相交(可見)的信息。

如果entry.isIntersecting為true,則意味著最后一張卡片現(xiàn)在可見:

  1. 使用 setListItems 將新項(xiàng)目添加到列表中。
  2. 取消觀察當(dāng)前元素(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)開始觀察它。

觀察者會(huì)監(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 創(chuàng)建的所有觀察者。

這確保了當(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%可見時(shí),觀察者的回調(diào)
運(yùn)行。

3。添加項(xiàng)目

回調(diào)將新項(xiàng)目添加到列表中 (setListItems)。

4。重復(fù)

觀察者與舊的最后一張卡斷開連接并附加到
新的最后一張卡。

Reactjs Tutorial : Infinite scrolling with Intersection Observer.

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

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

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

謝謝。

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

本站聲明
本文內(nèi)容由網(wǎng)友自發(fā)貢獻(xiàn),版權(quán)歸原作者所有,本站不承擔(dān)相應(yīng)法律責(zé)任。如您發(fā)現(xiàn)有涉嫌抄襲侵權(quán)的內(nèi)容,請(qǐng)聯(lián)系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

用于從照片中去除衣服的在線人工智能工具。

Clothoff.io

Clothoff.io

AI脫衣機(jī)

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集成開發(fā)環(huán)境

Dreamweaver CS6

Dreamweaver CS6

視覺化網(wǎng)頁開發(fā)工具

SublimeText3 Mac版

SublimeText3 Mac版

神級(jí)代碼編輯軟件(SublimeText3)

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

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

JavaScript評(píng)論:簡(jiǎn)短說明 JavaScript評(píng)論:簡(jiǎn)短說明 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開始;3.手動(dòng)格式化日期需拼接字符串,也可使用第三方庫(kù);4.處理時(shí)區(qū)問題建議使用支持時(shí)區(qū)的庫(kù),如Luxon。掌握這些要點(diǎn)能有效避免常見錯(cuò)誤。

JavaScript與Java:開發(fā)人員的全面比較 JavaScript與Java:開發(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ù)類型 JavaScript:探索用于高效編碼的數(shù)據(jù)類型 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.事件捕獲通過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)用戶操作的時(shí)機(jī)和方式。

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

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

See all articles