作者:互联网 时间: 2026-09-11 12:30:01
工作中遇到相关需求时,react-use-measure值得先读说明,因为它主要用于 测量视图边界的实用程序。这类界面与前端开发工具真正难在视觉还原、交互状态和响应式细节容易遗漏,仓库说明只能作为第一层证据。短测时我会选一个包含多状态的真实组件完成实现,并保留尺寸、状态、可访问性、资源和不同视口表现的结果,方便团队复盘。它对愿意逐状态验收界面质量的前端团队更有价值,但正式采用前仍要复查许可证、近期提交和问题区回应。
yarn add react-use-measure
这个小工具将测量您引用的视图的边界(例如宽度、高度、顶部、左侧)。它是反应性的,可以响应大小、窗口滚动和嵌套区域滚动的变化。
为什么我们需要这个钩子?
因为有 没有简单的方法 来获取相对视图坐标。是的,有 getBoundingClientRect,但是当您的内容位于其偏移量被简单忽略的滚动区域内(以及页面滚动)时,它不起作用。更糟糕的是,鼠标坐标是相对于视口(包含页面的可见矩形)的。例如,没有简单的方法可以知道鼠标悬停在元素的 upper/left 角上。这个钩子帮你解决了。
您可以在这里尝试现场演示:https://codesandbox.io/s/musing-kare-4fblz
用途
import useMeasure from 'react-use-measure'
function App() {
const [ref, bounds] = useMeasure()
// consider that knowing bounds is only possible *after* the view renders
// so you'll get zero values on the first run and be informed later
return
}
API
interface RectReadOnly {
readonly x: number
readonly y: number
readonly width: number
readonly height: number
readonly top: number
readonly right: number
readonly bottom: number
readonly left: number
}
type Options = {
// Debounce events in milliseconds
debounce?: number | { scroll: number; resize: number }
// React to nested scroll changes, don't use this if you know your view is static
scroll?: boolean
// You can optionally inject a resize-observer polyfill
polyfill?: { new (cb: ResizeObserverCallback): ResizeObserver }
// Measure size using offsetHeight and offsetWidth to ignore parent scale transforms
offsetSize?: boolean
}
useMeasure(
options: Options = { debounce: 0, scroll: false }
): [React.MutableRefObject<HTMLElement | SVGElement>, RectReadOnly]
⚠注意事项
调整大小观察者填充
该库依赖于调整大小观察者。如果您需要填充,您可以污染 window 对象或使用配置选项干净地注入它。我们推荐 @juggle/resize-observer。
import { ResizeObserver } from '@juggle/resize-observer'
function App() {
const [ref, bounds] = useMeasure({ polyfill: ResizeObserver })
多个参考文献
useMeasure 当前返回其自己的引用。我们这样做是因为我们使用功能引用来进行卸载跟踪。如果您需要在同一元素上拥有自己的引用,请使用 React-merge-refs。