useSize
监听元素/ window 尺寸变化 Hook
代码演示
监听元素变化
width: 0
height: 0
height: 0
当前元素 border: 10px, padding: 10px
Live Editor
监听窗口尺寸变化
width: 0
height: 0
height: 0
Live Editor
API
type UseSize = (target: React.MutableRefObject<Element> | Element | Window,watcherOrOptions?: Watcher | Option,options?: Option) => Size
target
可以是以下三种对象:
Dom ref
Element
window
watcher
type Watcher = (newSize: Size, oldSize: Size) => void | boolean
监听尺寸变化回调函数,函数返回 true
则更新组件;返回 false
,则不更新组件;如果没有返回值,根据依赖标记按需更新(比如只使用了返回的 width
,当且仅当 width
变化时,才更新组件)
Options
参数 | 说明 | 必选 | 类型 | 默认值 |
---|---|---|---|---|
box | 选择那种盒子的尺寸,content-box 或 border-box | - | content-box | border-box | border-box |
Size
参数 | 说明 | 类型 |
---|---|---|
width | 宽度 | number |
height | 高度 | number |