useScrollIntoView
類似於 element.scrollIntoView() 的 React Hook
useScrollIntoView 提供程式化的平滑捲動功能,將目標元素捲動到可視範圍內。它回傳一個物件,包含 scrollIntoView 函式和 cancel 函式。支援可設定的動畫時長、緩動函式和偏移量,並可在清單上下文中防止內容跳動。
使用場景
- 在表單驗證失敗時將使用者捲動到第一個錯誤欄位
- 實作「跳轉到頂部」或「跳轉到章節」按鈕
- 在清單中添加新項目後自動捲動以顯示新增內容
注意事項
- SSR 安全:在伺服器端渲染時回傳空操作函式。伺服器上不會進行 DOM 捲動。
- 可取消:設定
cancelable: true(預設)允許使用者透過手動捲動中斷捲動動畫。設定isList: true可防止清單中的內容跳動。 - 相關 hooks:另請參閱
useScroll追蹤捲動位置和狀態,以及useScrollLock完全防止捲動。
Usage
Live Editor
function Demo() { const targetRef = useRef<HTMLParagraphElement>(null); const { scrollIntoView } = useScrollIntoView(targetRef, { offset: 60, }); return ( <div> <button onClick={() => scrollIntoView({ alignment: "center" })}> 滾動到目標 </button> <div style={{ height: "50vh" }} /> <p ref={targetRef}>你好,這裡是目標</p> </div> ); }
Result
API
useScrollIntoView
Returns
{ scrollIntoView: (animation?: UseScrollIntoViewAnimation | undefined) => void; cancel: () => void; }: 包含以下元素的對象:
- scrollIntoView:滚動進入視口函數。
- cancel: 取消滚動函數。
Arguments
| 參數名 | 描述 | 類型 | 預設值 |
|---|---|---|---|
| targetElement | dom对象 | BasicTarget<HTMLElement> (必填) | - |
| params | 可选参数 | UseScrollIntoViewParams | undefined | - |
| scrollElement | 滚动容器 | BasicTarget<HTMLElement> | - |
UseScrollIntoViewAnimation
| 參數名 | 描述 | 類型 | 預設值 |
|---|---|---|---|
| alignment | 基于当前轴的目标元素相对于父元素的对齐方式 | 'start' | 'end' | 'center' | - |
UseScrollIntoViewParams
| 參數名 | 描述 | 類型 | 預設值 |
|---|---|---|---|
| onScrollFinish | 滚动完成回调 | () => void | - |
| duration | 滚动时间 | number | 1250 |
| axis | 滚动方向 | 'x' | 'y' | y |
| easing | 自定义缓和数学函数 | (t: number) => number | (t: number) => t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t |
| offset | 最近的边缘和元素之间的附加距离 | number | 0 |
| cancelable | 指示动画是否可能因用户滚动而中断 | boolean | true |
| 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;