useInViewport 源码简单分析记录以及在项目中的使用方式。
ahooks的实现方式是通过IntersectionObserver
浏览器兼容问题使用npm IntersectionObserver polyfill
import 'intersection-observer'; // polyfill浏览器兼容
import { useState } from 'react';
import type { BasicTarget } from '../utils/domTarget';
import { getTargetElement } from '../utils/domTarget';
import useEffectWithTarget from '../utils/useEffectWithTarget';
export interface Options {
rootMargin?: string;
threshold?: number | number[];
root?: BasicTarget<Element>;
}
function useInViewport(target: BasicTarget, options?: Options) {
const [state, setState] = useState<boolean>(); // 是否可见
const [ratio, setRatio] = useState<number>(); // 当前可见比例,在每次到达 `options.threshold` 设置节点时更新
useEffectWithTarget(
() => {
const el = getTargetElement(target);
if (!el) {
return;
}
const observer = new IntersectionObserver(
(entries) => {
for (const entry of entries) {
setRatio(entry.intersectionRatio); // 偏移量
setState(entry.isIntersecting); // 是否出现在窗口中
}
},
{
...options,
root: getTargetElement(options?.root),
},
);
observer.observe(el);
return () => {
observer.disconnect();
};
},
[options?.rootMargin, options?.threshold],
target,
);
return [state, ratio] as const;
}
export default useInViewport;
IntersectionObserver
IntersectionObserver
接口(从属于 Intersection Observer API)提供了一种异步观察目标元素与其祖先元素或顶级文档视口(viewport)交叉状态的方法。其祖先元素或视口被称为根(root)。
当一个 IntersectionObserver
对象被创建时,其被配置为监听根中一段给定比例的可见区域。一旦 IntersectionObserver
被创建,则无法更改其配置,所以一个给定的观察者对象只能用来监听可见区域的特定变化值;然而,你可以在同一个观察者对象中配置监听多个目标元素。
构造函数
-
创建一个新的
IntersectionObserver
对象,当其监听到目标元素的可见部分(的比例)超过了一个或多个阈值(threshold)时,会执行指定的回调函数。
实例属性
-
IntersectionObserver.rootMargin
只读计算交叉时添加到根边界盒 (en-US)的矩形偏移量,可以有效的缩小或扩大根的判定范围从而满足计算需要。此属性返回的值可能与调用构造函数时指定的值不同,因此可能需要更改该值,以匹配内部要求。所有的偏移量均可用像素(
px
)或百分比(%
)来表达,默认值为 “0px 0px 0px 0px”。 -
IntersectionObserver.thresholds
只读一个包含阈值的列表,按升序排列,列表中的每个阈值都是监听对象的交叉区域与边界区域的比率。当监听对象的任何阈值被越过时,都会生成一个通知(Notification)。如果构造器未传入值,则默认值为 0。
实例方法
-
IntersectionObserver.disconnect()
使
IntersectionObserver
对象停止监听目标。 -
IntersectionObserver.observe()
使
IntersectionObserver
开始监听一个目标元素。 -
IntersectionObserver.takeRecords()
返回所有观察目标的
IntersectionObserverEntry
对象数组。 -
IntersectionObserver.unobserve()
使
IntersectionObserver
停止监听特定目标元素。
示例
const intersectionObserver = new IntersectionObserver((entries) => {
// 如果 intersectionRatio 为 0,则目标在视野外,
// 我们不需要做任何事情。
if (entries[0].intersectionRatio <= 0) return;
loadItems(10);
console.log('Loaded new items');
});
// 开始监听
intersectionObserver.observe(document.querySelector('.scrollerFooter'));
项目中使用案例:
正常写滚动分页需要监听onScroll事件:
然后计算scrollHeight - offsetHeight - scrollTop的值
然后还需要注意性能优化使用throttle控制方法执行频率
function onScroll(){
// const maxScrollTop = document.querySelector(".App").scrollHeight
// const innerHeight= document.querySelector(".App").offsetHeight;
const currentScrollTop = document.querySelector(".App").scrollTop; // 滚动元素上面超出的距离
const maxScrollTop = document.querySelector(".App").scrollHeight - document.querySelector(".App").offsetHeight;
// 滚动页面长度 - 此容器高度 = 滚动元素上面超出的距离 + 底部未出现的高度
if (maxScrollTop - currentScrollTop < 20) {
handleNextPage() // 请求下一页
}
}
但是我们可以换一个思路,我们在列表的底部加上一个分页展示的div,当前div出现在窗口内说明列表滑动到底了,我们需要重新请求数据。
/**
* 滑动分页
*/
import React from "react";
import { useInViewport } from "ahooks";
import styles from "./index.module.css";
type ScrollPaginationProps = {
isEnd: boolean; // 查看当前列表有没有到底、如果已经到底了不重复触发回调
visible: boolean; // 应用场景主要是数据小于一页不展示分页组件
onScrollEnd: () => void;
};
const ScrollPagination: React.FC<ScrollPaginationProps> = ({
visible,
isEnd,
onScrollEnd,
}) => {
const ref = React.useRef(null);
const [inViewport] = useInViewport(ref);
React.useEffect(() => {
if (onScrollEnd && inViewport && !isEnd) {
onScrollEnd();
}
}, [inViewport, onScrollEnd, isEnd]);
/**
* 控制当前元素展示不展示
*/
if (!visible) {
return null;
}
if (!isEnd) {
return (
<div className={styles.poScollPagination} ref={ref}>
loading。。。
</div>
);
}
return (
<div className={styles.poScollPagination} ref={ref}>
no more。。。
</div>
);
};
ScrollPagination.displayName = "ScrollPagination";
export default React.memo(ScrollPagination);