This commit is contained in:
Archer
2023-11-20 19:20:55 +08:00
committed by GitHub
parent 9c4eabfc9e
commit 0558379ddb
26 changed files with 571 additions and 497 deletions

View File

@@ -0,0 +1,28 @@
import { useEffect, useRef, useState } from 'react';
export function useSticky(props?: { threshold?: number }) {
const { threshold = 20 } = props || {};
const parentRef = useRef<HTMLDivElement>(null);
const divRef = useRef<HTMLDivElement>(null);
const [isSticky, setIsSticky] = useState(false);
useEffect(() => {
const cb = () => {
if (!divRef.current) return;
const rect = divRef.current.getBoundingClientRect();
const isSticky = rect.top <= threshold;
setIsSticky(isSticky);
};
parentRef.current?.addEventListener('scroll', cb);
return () => {
parentRef.current?.removeEventListener('scroll', cb);
};
}, [threshold]);
return {
parentRef,
divRef,
isSticky
};
}