useOrientation
跟踪用户设备的屏幕方向。
useOrientation 封装了 Screen Orientation API,用于响应式地跟踪设备的方向角度和类型(例如 portrait-primary、landscape-secondary)。它返回一个包含当前方向状态、lock 函数(用于锁定屏幕到特定方向)和 unlock 函数的元组。方向状态包括 angle(角度)和 type。
使用场景
- 当设备在纵向和横向之间旋转时调整 UI 布局
- 为游戏、视频播放器或演示模式锁定屏幕方向
- 显示方向相关的内容或触发布局重新计算
注意事项
- SSR 安全:在服务端渲染期间返回默认方向值(
angle: 0、type: undefined)。服务端不会访问screen.orientation。 - 方向锁定:在大多数浏览器中,
lock函数需要页面处于全屏模式。配合useFullscreen使用以实现可靠的方向锁定。 - 相关 hooks:参见
useMobileLandscape了解简化的布尔值检查,以及useMediaQuery了解自定义的基于方向的媒体查询。
Usage
Live Editor
function Demo() { const [state] = useOrientation(); return <pre>{JSON.stringify(state, null, 2)}</pre>; };
Result
API
useOrientation
Returns
readonly [UseOrientationState, (type: UseOrientationLockType) => any, () => void]: 包含以下元素的元组:
- 方向状态。
- 锁定方向。
- 解锁方向。
Arguments
| 参数名 | 描述 | 类型 | 默认值 |
|---|---|---|---|
| initialState | 初始值 | UseOrientationState | undefined | - |
UseOrientationState
| 参数名 | 描述 | 类型 | 默认值 |
|---|---|---|---|
| angle | 角度 | number (必填) | - |
| type | 方向类型 | UseOrientationType | undefined (必填) | - |
UseOrientationType
Type
export type UseOrientationType = | 'portrait-primary' | 'portrait-secondary' | 'landscape-primary' | 'landscape-secondary'
UseOrientationLockType
Type
export type UseOrientationLockType = | 'any' | 'natural' | 'landscape' | 'portrait' | 'portrait-primary' | 'portrait-secondary' | 'landscape-primary' | 'landscape-secondary'