发布于 2026-01-06 0 阅读
0

只需几行代码即可实现无限滚动!

只需几行代码即可实现无限滚动!

想用几行代码移除那些实现无限滚动或懒加载的臃肿插件吗?那我有个好东西要给你展示。隆重推出Intersection Observer!

无限滚动示例

交叉路口观察器是如何工作的?

简单来说,它就像魔法一样神奇🎊 就是这样!我们继续……

如果你想了解更多,那就太好了!这是一个接受回调函数的 Web API。当目标元素与视口或指定元素(我们称之为根元素或根)相交时,会触发此回调函数。

我该如何使用它?

通过传递回调函数和配置对象来创建 IntersectionObserver 对象。

配置(也称为选项)接受 3 个值:rootrootMarginthreshold,其格式如下所示。

// Defining config
let config = {
    root: document.querySelector('#scrollArea'),
    rootMargin: '0px',
    threshold: 1.0
}

// What action needs to be taken
let callback = () => {
    // Here you specify what needs to be done
    // More on this later
}

// Creating an observer object
let observer = new IntersectionObserver(callback, config)
Enter fullscreen mode Exit fullscreen mode

在举例之前,让我先简要解释一下 config 中的每个值的作用。

  • 根:它用作视口,用于检查目标的可见性。默认情况下,如果null传递了该参数,则使用浏览器视口。
  • 根边距:它是根周围的边距。
  • 阈值:称为交集比率,范围从 0.0 到 1.0,其中 1.0 表示目标在根内 100% 可见。

现在我们来谈谈回调函数。回调函数接受一个数组类型的参数。之所以使用数组,是因为你可以向同一个观察者添加多个目标(具有相同 ID 名称的实体) 。我们使用`isIntersecting`属性来判断可观察元素是否可见。

例子

解释就到这里,我们来看一个例子。你可以在这里查看完整内容。

...

const App = () => {
    // Create an observer object
    const observer = useRef(null);
    observer.current = new IntersectionObserver(
    (entries) => {
        // entries is of type array
        entries.forEach((entry) => {
        // this will tell if the element is visible or not
        if (!entry.isIntersecting) {
            return;
        }
        // Do something
    })
    }, {
        root: document.querySelector("#App"),
        rootMargin: "0px",
        threshold: 0.3,
    });

    ...

    // ComponentDidMount, Make sure to observe the element after render
    useEffect(() => {
        observer.current.observe(document.querySelector("#observe-this"));
    }, []);

    ...

   return (
        <div className="App">

            ...

            {/* When this div is visible, fetch new data */}
            <div id="observe-this"></div>

            ...

        </div>
    );
};

...
Enter fullscreen mode Exit fullscreen mode

上面的例子应该不言自明了。如果还不清楚,那我就简单总结一下。

  • 创建一个观察者对象;如果是基于类的组件,则在构造函数中添加对象创建代码片段。
  • 创建观察者时,需要传递一个回调函数和一个选项对象。这将告诉观察者以下内容:
    • 回调触发时需要做什么?
    • 何时应该调用回调函数?
    • 可见区域是什么?
  • 当组件渲染时,指向要观察的元素。

参考

文章来源:https://dev.to/darylaranha/get-infinite-scrolling-in-just-few-lines-of-code-368l