交叉观察器IntersectionObserver对象实战使用

交叉观察器IntersectionObserver对象实战使用

用IntersectionObserver判断滚动页面是否到达底部

import { Toast } from "antd-mobile";
import { useRef, useLayoutEffect, useMemo } from "react";
import { v4 as uuid } from "uuid";

/**
 * 用IntersectionObserver判断滚动页面是否到达底部
 * @returns
 */
const MyPage = () => {
  const bottomRef = useRef<HTMLDivElement | null>(null);

  const list = useMemo(() => {
    // 用 uuid 生成 key,且去掉中间的横杠,只保留前 18 位
    // 注意:生成 200 个空数组,要先 fill(0),否则 map 不会执行
    return new Array(200)
      .fill(0)
      .map(() => ({ key: uuid().replace(/-/g, "").substring(0, 18) }));
  }, []);

  useLayoutEffect(() => {
    const observer = new IntersectionObserver(
      (entries) => {
        if (entries[0].isIntersecting) {
          console.log("到底了");
          Toast.show({
            position: "center",
            content: "到底了",
          });
        }
      },
      {
        root: document.getElementById("myComponent"), // 使用滚动视口作为根
        rootMargin: "0px",
        threshold: 1.0, // 完全进入视口时触发
      }
    );

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

    return () => {
      if (bottomRef.current) {
        // eslint-disable-next-line react-hooks/exhaustive-deps
        observer.unobserve(bottomRef.current);
      }
    };
  }, []);

  return (
    <div
      id="myComponent"
      style={{
        height: "calc(100vh - 48px)",
        overflowY: "auto",
        padding: "24px",
      }}
    >
      {Array.isArray(list) &&
        list.map((item, index) => {
          return <div key={item.key}>{`${index} --> ${item?.key}`}</div>;
        })}
       // 设置列表底部元素,高度为 1px 即可
      <div ref={bottomRef} style={{ height: "1px" }} />
    </div>
  );
};

export default MyPage;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值