ReactのuseIntersectionObserverフック

ReactReactBeginner
今すぐ練習

This tutorial is from open-source community. Access the source code

💡 このチュートリアルは英語版からAIによって翻訳されています。原文を確認するには、 ここをクリックしてください

はじめに

この実験では、React で useIntersectionObserver フックを使用して、特定の要素の表示状態の変化を監視する方法を学びます。このフックは、要素が画面上に表示されるタイミングを追跡し、それに応じて特定のアクションをトリガーするために使用できます。この実験が終了すると、React プロジェクトでこのフックを実装して、よりインタラクティブで動的なユーザー インターフェイスを作成できるようになります。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL react(("React")) -.-> react/StateManagementGroup(["State Management"]) react(("React")) -.-> react/FundamentalsGroup(["Fundamentals"]) react(("React")) -.-> react/AdvancedConceptsGroup(["Advanced Concepts"]) react(("React")) -.-> react/StylingGroup(["Styling"]) react/FundamentalsGroup -.-> react/jsx("JSX") react/FundamentalsGroup -.-> react/event_handling("Handling Events") react/FundamentalsGroup -.-> react/conditional_render("Conditional Rendering") react/AdvancedConceptsGroup -.-> react/hooks("React Hooks") react/StylingGroup -.-> react/css_in_react("CSS in React") react/StateManagementGroup -.-> react/use_state_reducer("Using useState and useReducer") subgraph Lab Skills react/jsx -.-> lab-38389{{"ReactのuseIntersectionObserverフック"}} react/event_handling -.-> lab-38389{{"ReactのuseIntersectionObserverフック"}} react/conditional_render -.-> lab-38389{{"ReactのuseIntersectionObserverフック"}} react/hooks -.-> lab-38389{{"ReactのuseIntersectionObserverフック"}} react/css_in_react -.-> lab-38389{{"ReactのuseIntersectionObserverフック"}} react/use_state_reducer -.-> lab-38389{{"ReactのuseIntersectionObserverフック"}} end

React useIntersectionObserver フック

VM には既に index.htmlscript.js が用意されています。一般的には、script.jsstyle.css にのみコードを追加すればよいです。

特定の要素の表示状態の変化を監視するには、次の手順に従います。

  1. useState() フックを使用して、特定の要素の交差値を格納します。
  2. 与えられた オプション と適切なコールバックを持つ IntersectionObserver を作成して、isIntersecting 状態変数を更新します。
  3. useEffect() フックを使用して、コンポーネントのマウント時に IntersectionObserver.observe() を呼び出し、アンマウント時に IntersectionObserver.unobserve() を使用してクリーンアップします。

以下は、実装例です。

const useIntersectionObserver = (ref, options) => {
  const [isIntersecting, setIsIntersecting] = React.useState(false);

  React.useEffect(() => {
    const observer = new IntersectionObserver(([entry]) => {
      setIsIntersecting(entry.isIntersecting);
    }, options);

    if (ref.current) {
      observer.observe(ref.current);
    }

    return () => {
      observer.unobserve(ref.current);
    };
  }, [ref, options]);

  return isIntersecting;
};

useIntersectionObserver フックを次のように使用できます。

const MyApp = () => {
  const ref = React.useRef();
  const onScreen = useIntersectionObserver(ref, { threshold: 0.5 });

  return (
    <div>
      <div style={{ height: "100vh" }}>Scroll down</div>
      <div style={{ height: "100vh" }} ref={ref}>
        <p>{onScreen ? "Element is on screen." : "Scroll more!"}</p>
      </div>
    </div>
  );
};

ReactDOM.createRoot(document.getElementById("root")).render(<MyApp />);

右下隅の「Go Live」をクリックして、ポート 8080 でウェブ サービスを実行してください。その後、Web 8080 タブを更新して、ウェブ ページをプレビューできます。

まとめ

おめでとうございます!あなたは React useIntersectionObserver フックの実験を完了しました。あなたのスキルを向上させるために、LabEx でさらに多くの実験を行って練習することができます。