찾다
웹 프론트엔드JS 튜토리얼Reactjs 튜토리얼: Intersection Observer를 사용한 무한 스크롤.

무한 스크롤이란 무엇이며 이에 대한 필요성은 무엇입니까?

스크롤은 웹페이지 콘텐츠의 일부를 가로 또는 세로(대부분의 경우)로 이동하는 사용자 동작입니다.

이 기사를 읽는 동안 여러분도 그렇게 하게 될 것입니다.

Infinite는 웹페이지를 아래로 스크롤할 때 새로운 콘텐츠가 자동으로 로드된다는 의미입니다.

그렇습니다. 그런데 왜 구현해야 할까요?

검색 가능성

즐겨찾는 전자상거래 매장에서 블랙 프라이데이 세일을 한다고 가정해 보세요.

탐색 페이지에서 몇 가지 제품을 찾았지만 더 많은 제품 대신 웹페이지 하단으로 스크롤하면 다음 제품 목록으로 이동하는 버튼을 발견했습니다.

새 제품을 만나보실 수 있습니다. (단, 해당 액션 버튼이 있는 경우에만 해당됩니다.)

무한 스크롤은 사용자가 놓쳤을 수도 있는 더 많은 콘텐츠를 찾는 데 도움이 됩니다.

구현

무한 스크롤을 구현하려면 사용자가 페이지 하단이나 컨테이너에 도달했는지 계속 확인해야 합니다.

그러나 스크롤 위치를 감지하는 데는 비용이 많이 들고 브라우저와 장치가 다르기 때문에 위치 값을 신뢰할 수 없습니다.

그래서 한 가지 방법은 페이지의 마지막 콘텐츠(요소)와 뷰포트 또는 컨테이너와의 교차점을 보는 것입니다.

교차점은 어떻게 찾나요?

교차점 관찰자

콘텐츠나 목록의 끝에서 요소를 관찰할 수 있는 웹 API입니다.

요소("sentinel")가 표시되면(뷰포트와 교차하고 콜백 함수가 트리거됩니다.

이 기능을 통해 더 많은 데이터를 가져와 웹페이지에 로드할 수 있습니다.

이 전체 관찰은 비동기식으로 이루어지며, 이는 메인 스레드에 미치는 영향을 최소화합니다.


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 페이지에 현재 표시되는 항목의 배열을 보유합니다.

비. 목록 렌더링 및 참조 할당
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에 대한 고유한 키를 갖습니다.

기음. 지난 포스팅(항목)을 관찰합니다.
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를 나타냅니다.
루트가 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인 경우 이제 마지막 카드가 표시된다는 의미입니다.

  1. setListItems를 사용하여 목록에 새 항목을 추가합니다.
  2. 중복 트리거를 방지하려면 현재 요소(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에 의해 생성된 모든 관찰자를 제거합니다.

이렇게 하면 구성 요소가 마운트 해제되거나 다시 렌더링될 때 이전 관찰자가 정리됩니다.


Reactjs Tutorial : Infinite scrolling with Intersection Observer.

각 단계에서는 어떤 일이 발생하나요?

1. 사용자 스크롤

사용자가 스크롤하면 마지막 카드가 표시됩니다

2. 교차점 관찰자 트리거

마지막 카드의 50%가 보이면 관찰자의 콜백
달려갑니다.

3. 항목 추가

콜백은 목록(setListItems)에 새 항목을 추가합니다.

4. 반복

관찰자는 이전 마지막 카드의 연결을 끊고
에 연결합니다. 새로운 마지막 카드입니다.

Reactjs Tutorial : Infinite scrolling with Intersection Observer.

이것이 Intersection Observer를 사용하여 무한 스크롤을 구현하는 방법입니다.

도움이 되었기를 바랍니다 :)

감사합니다.

위 내용은 Reactjs 튜토리얼: Intersection Observer를 사용한 무한 스크롤.의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
JavaScript 데이터 유형 : 브라우저와 Nodejs 사이에 차이가 있습니까?JavaScript 데이터 유형 : 브라우저와 Nodejs 사이에 차이가 있습니까?May 14, 2025 am 12:15 AM

JavaScript 코어 데이터 유형은 브라우저 및 Node.js에서 일관되지만 추가 유형과 다르게 처리됩니다. 1) 글로벌 객체는 브라우저의 창이고 node.js의 글로벌입니다. 2) 이진 데이터를 처리하는 데 사용되는 Node.js의 고유 버퍼 객체. 3) 성능 및 시간 처리에는 차이가 있으며 환경에 따라 코드를 조정해야합니다.

JavaScript 댓글 : / / * * /사용 안내서JavaScript 댓글 : / / * * /사용 안내서May 13, 2025 pm 03:49 PM

javaScriptUSTWOTYPESOFSOFCOMMENTS : 단일 라인 (//) 및 multi-line (//)

Python vs. JavaScript : 개발자를위한 비교 분석Python vs. JavaScript : 개발자를위한 비교 분석May 09, 2025 am 12:22 AM

Python과 JavaScript의 주요 차이점은 유형 시스템 및 응용 프로그램 시나리오입니다. 1. Python은 과학 컴퓨팅 및 데이터 분석에 적합한 동적 유형을 사용합니다. 2. JavaScript는 약한 유형을 채택하며 프론트 엔드 및 풀 스택 개발에 널리 사용됩니다. 두 사람은 비동기 프로그래밍 및 성능 최적화에서 고유 한 장점을 가지고 있으며 선택할 때 프로젝트 요구 사항에 따라 결정해야합니다.

Python vs. JavaScript : 작업에 적합한 도구 선택Python vs. JavaScript : 작업에 적합한 도구 선택May 08, 2025 am 12:10 AM

Python 또는 JavaScript를 선택할지 여부는 프로젝트 유형에 따라 다릅니다. 1) 데이터 과학 및 자동화 작업을 위해 Python을 선택하십시오. 2) 프론트 엔드 및 풀 스택 개발을 위해 JavaScript를 선택하십시오. Python은 데이터 처리 및 자동화 분야에서 강력한 라이브러리에 선호되는 반면 JavaScript는 웹 상호 작용 및 전체 스택 개발의 장점에 없어서는 안될 필수입니다.

파이썬 및 자바 스크립트 : 각각의 강점을 이해합니다파이썬 및 자바 스크립트 : 각각의 강점을 이해합니다May 06, 2025 am 12:15 AM

파이썬과 자바 스크립트는 각각 고유 한 장점이 있으며 선택은 프로젝트 요구와 개인 선호도에 따라 다릅니다. 1. Python은 간결한 구문으로 데이터 과학 및 백엔드 개발에 적합하지만 실행 속도가 느립니다. 2. JavaScript는 프론트 엔드 개발의 모든 곳에 있으며 강력한 비동기 프로그래밍 기능을 가지고 있습니다. node.js는 풀 스택 개발에 적합하지만 구문은 복잡하고 오류가 발생할 수 있습니다.

JavaScript의 핵심 : C 또는 C에 구축 되었습니까?JavaScript의 핵심 : C 또는 C에 구축 되었습니까?May 05, 2025 am 12:07 AM

javaScriptisNotBuiltoncorc; it'SangretedLanguageThatrunsonOngineStenWrittenInc .1) javaScriptWasDesignEdasAlightweight, 해석 hanguageforwebbrowsers.2) Endinesevolvedfromsimpleplemporectreterstoccilpilers, 전기적으로 개선된다.

JavaScript 응용 프로그램 : 프론트 엔드에서 백엔드까지JavaScript 응용 프로그램 : 프론트 엔드에서 백엔드까지May 04, 2025 am 12:12 AM

JavaScript는 프론트 엔드 및 백엔드 개발에 사용할 수 있습니다. 프론트 엔드는 DOM 작업을 통해 사용자 경험을 향상시키고 백엔드는 Node.js를 통해 서버 작업을 처리합니다. 1. 프론트 엔드 예 : 웹 페이지 텍스트의 내용을 변경하십시오. 2. 백엔드 예제 : node.js 서버를 만듭니다.

Python vs. JavaScript : 어떤 언어를 배워야합니까?Python vs. JavaScript : 어떤 언어를 배워야합니까?May 03, 2025 am 12:10 AM

Python 또는 JavaScript는 경력 개발, 학습 곡선 및 생태계를 기반으로해야합니다. 1) 경력 개발 : Python은 데이터 과학 및 백엔드 개발에 적합한 반면 JavaScript는 프론트 엔드 및 풀 스택 개발에 적합합니다. 2) 학습 곡선 : Python 구문은 간결하며 초보자에게 적합합니다. JavaScript Syntax는 유연합니다. 3) 생태계 : Python에는 풍부한 과학 컴퓨팅 라이브러리가 있으며 JavaScript는 강력한 프론트 엔드 프레임 워크를 가지고 있습니다.

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 Linux 새 버전

SublimeText3 Linux 새 버전

SublimeText3 Linux 최신 버전

맨티스BT

맨티스BT

Mantis는 제품 결함 추적을 돕기 위해 설계된 배포하기 쉬운 웹 기반 결함 추적 도구입니다. PHP, MySQL 및 웹 서버가 필요합니다. 데모 및 호스팅 서비스를 확인해 보세요.

Eclipse용 SAP NetWeaver 서버 어댑터

Eclipse용 SAP NetWeaver 서버 어댑터

Eclipse를 SAP NetWeaver 애플리케이션 서버와 통합합니다.