实例

import { useEffect, useRef } from 'react';
import { Spin } from 'antd';
import type { FsFC } from './types';
import './index.less';
type LoadMoreProps = {
  root?: Element | null; // 跟哪个元素重叠不传默认则是 整个浏览器窗口,一般是父元素
  isLoading: boolean; // 用来判断如果 没有在请求列表才回执行
  more: () => void;
};
const LoadMore: FsFC<LoadMoreProps> = ({ root = null, isLoading, more }) => {
  const loadMoreRef = useRef(null);
  /** 建立加载更多观察者 */
  const loadMoreOb = () => {
    if (!loadMoreRef.current) {
      return;
    }
    const ob = new IntersectionObserver(
      (entries) => {
        const [entry] = entries;
        // 有重叠,并且没有在请求
        if (entry.isIntersecting && !isLoading) {
          more();
        }
      },
      {
        root,
        threshold: 1,
      },
    );
    ob.observe(loadMoreRef.current);
  };
  useEffect(() => {
    loadMoreOb();
  }, []);
  return (
    <div className="load-more" ref={loadMoreRef}>
      <Spin />
    </div>
  );
};
export default LoadMore;

文中注释已对代码进行详解说明,以上就是IntersectionObserver实现加载更多组件demo的详细内容,更多关于IntersectionObserver加载组件的资料请关注其它相关文章!

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。