useElementVisibility
追踪视窗内元素可见性的 React Hook。这是 useIntersectionObserver
的一个封装器
Usage
实时编辑器
function Demo() { const ref = useRef<HTMLDivElement>(null); const [visible, stop] = useElementVisibility(ref); return ( <div> <p>Info on the right bottom corner</p> <div ref={ref} style={{ borderWidth: 2, borderStyle: "solid", padding: "1rem", }} > Target Element (scroll down) </div> <button onClick={() => { stop(); }} > Stop </button> <div style={{ borderWidth: 2, borderStyle: "solid", padding: "1rem", position: "fixed", bottom: 0, right: 0, zIndex: 100, }} > Element {visible ? "inside" : "outside"} the viewport </div> </div> ); };
结果
Loading...
API
useElementVisibility
Returns
readonly [boolean, () => void]
: 包含以下元素的元组:
- 当前元素是否可见。
- 停止监听函数。
Arguments
参数名 | 描述 | 类型 | 默认值 |
---|---|---|---|
target | dom对象 | BasicTarget<HTMLElement | SVGElement> (必填) | - |
options | 传递给 intersectionObserver 的选项 | IntersectionObserverInit | undefined | - |
BasicTarget
export type BasicTarget<T extends TargetType = Element> = (() => TargetValue<T>) | TargetValue<T> | MutableRefObject<TargetValue<T>>;
TargetValue
type TargetValue<T> = T | undefined | null;
TargetType
type TargetType = HTMLElement | Element | Window | Document | EventTarget;