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/StylingGroup(["Styling"]) react(("React")) -.-> react/StateManagementGroup(["State Management"]) react(("React")) -.-> react/FundamentalsGroup(["Fundamentals"]) react(("React")) -.-> react/AdvancedConceptsGroup(["Advanced Concepts"]) 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 钩子

虚拟机中已提供 index.htmlscript.js。一般来说,你只需在 script.jsstyle.css 中添加代码。

要观察给定元素的可见性变化,请执行以下步骤:

  1. 使用 useState() 钩子存储给定元素的交叉值。
  2. 使用给定的 options 创建一个 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" }}>向下滚动</div>
      <div style={{ height: "100vh" }} ref={ref}>
        <p>{onScreen ? "元素在屏幕上。" : "继续滚动!"}</p>
      </div>
    </div>
  );
};

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

请点击右下角的“上线”以在端口 8080 上运行网络服务。然后,你可以刷新“Web 8080”标签页来预览网页。

总结

恭喜你!你已经完成了 React 的 useIntersectionObserver 钩子实验。你可以在 LabEx 中练习更多实验来提升你的技能。