跳到主要内容

useInfiniteScroll

无限滚动

Usage

实时编辑器

function Demo() {
  const ref = useRef<HTMLDivElement>(null);
  const [data, setData] = useState([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);

  useInfiniteScroll(
    ref,
    () => {
      const length = data.length + 1;
      const newData = data.slice();
      if (newData.length === 400) {
        return;
      }
      newData.push(...Array.from({ length: 5 }, (_, i) => length + i));
      setData(newData);
    },
    { distance: 10 },
  );

  return (
    <div>
      <div ref={ref} style={{ width: 300, height: 300, overflow: "scroll" }}>
        {data.map(item => (
          <div key={item} style={{ padding: 12, border: "1px solid" }}>
            item-{item}
          </div>
        ))}
      </div>
    </div>
  );
};

结果
Loading...

API

useInfiniteScroll

Returns

void

Arguments

参数名描述类型默认值
targetdom元素BasicTarget<Element> (必填)-
onLoadMore加载更多函数UseInfiniteScrollLoadMore (必填)-
options可选参数UseInfiniteScrollOptions | undefined-

UseInfiniteScrollLoadMore

Returns

void | Promise<void>

Arguments

参数名描述类型默认值
stateuseScroll 返回的状态readonly [number, number, boolean, UseInfiniteScrollArrivedState, UseInfiniteScrollDirection] (必填)-

UseInfiniteScrollOptions

参数名描述类型默认值
distance元素底部与视口底部之间的最小距离number0
direction滚动方向'top' | 'bottom' | 'left' | 'right''bottom'
preserveScrollPosition加载更多项目时是否保留当前滚动位置boolean-
throttle滚动事件的节流时间,默认关闭。number0
idle滚动结束时的检查时间。当配置 throttle 时,此配置将设置为 (throttle +idle)。number-
offset将到达状态偏移 x 像素UseScrollOffset-
onScroll滚动的回调(e: Event) => void-
onStop滚动结束的回调(e: Event) => void-
eventListenerOptions滚动事件参数boolean | AddEventListenerOptions{capture: false, passive: true}

UseInfiniteScrollArrivedState

参数名描述类型默认值
left到达左边boolean (必填)-
right到达右边boolean (必填)-
top到达顶部boolean (必填)-
bottom到达底部boolean (必填)-

UseInfiniteScrollDirection

参数名描述类型默认值
left向左滚动boolean (必填)-
right向右滚动boolean (必填)-
top向上滚动boolean (必填)-
bottom向下滚动boolean (必填)-

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;

UseScrollOffset

export interface UseScrollOffset {
left?: number;
right?: number;
top?: number;
bottom?: number;
}