跳到主要内容

useScrollIntoView

类似于 element.scrollIntoView() 的 React Hook

Usage

实时编辑器

function Demo() {
  const targetRef = useRef<HTMLParagraphElement>(null);
  const { scrollIntoView } = useScrollIntoView(targetRef, {
    offset: 60,
  });

  return (
    <div>
      <button onClick={() => scrollIntoView({ alignment: "center" })}>
        Scroll to target
      </button>
      <div style={{ height: "50vh" }} />
      <p ref={targetRef}>Hello there</p>
    </div>
  );
}

结果
Loading...

API

useScrollIntoView

Returns

{ scrollIntoView: (animation?: UseScrollIntoViewAnimation | undefined) => void; cancel: () => void; }: 包含以下元素的对象:

  • scrollIntoView:滚动进入视口函数。
  • cancel: 取消滚动函数。

Arguments

参数名描述类型默认值
targetElementdom对象BasicTarget<HTMLElement> (必填)-
params可选参数UseScrollIntoViewParams | undefined-
scrollElement滚动容器BasicTarget<HTMLElement>-

UseScrollIntoViewAnimation

参数名描述类型默认值
alignment基于当前轴的目标元素相对于父元素的对齐方式'start' | 'end' | 'center'-

UseScrollIntoViewParams

参数名描述类型默认值
onScrollFinish滚动完成回调() => void-
duration滚动时间number1250
axis滚动方向'x' | 'y'y
easing自定义缓和数学函数(t: number) => number(t: number) => t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t
offset最近的边缘和元素之间的附加距离number0
cancelable指示动画是否可能因用户滚动而中断booleantrue
isList防止内容在具有多个目标的滚动列表中跳跃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;