基于事件的跨浏览器元素大小调整检测技术
元素大小调整就像是 2025 年一样! 实时演示现代浏览器现在具有原生支持,可通过 ResizeObserver 检测元素大小变化。此库利用 ResizeObserver 来帮助管理 React 应用程序中的元素大小变化。微小 2kb 使用 TypeScript 由 170 个仓库使用 每年产生 10000 万次下载 没有窗口的 resize 监听器! 没有超时! 您是否应该使用此库? 首先考虑 CSS 容器查询! 它们现在在所有主流浏览器中都能正常工作,并且可能通过纯 CSS 解决您的用例。CSS 容器查询示例 html css .post { container-type: inline-size; } / 卡标题的默认标题样式 / .card h2 { font-size: 1em; } / 如果容器大于 700px / @container (min-width: 700px) { .card h2 { font-size: 2em; } } 当您需要以下内容时,请使用此库: - 基于 JavaScript 的调整逻辑,提供完整的 TypeScript 支持 - 基于尺寸的复杂计算 - 集成到 React 状态/效果中 - 程序化控制调整行为 安装 bash npm install react-resize-detector OR yarn add react-resize-detector OR pnpm add react-resize-detector 快速入门基本用法 tsx import { useResizeDetector } from 'react-resize-detector'; const CustomComponent = () = { const { width, height, ref } = useResizeDetector(); return ; }; 使用调整回调 tsx import { useCallback } from 'react'; import { useResizeDetector, OnResizeCallback } from 'react-resize-detector'; const CustomComponent = () = { const onResize: OnResizeCallback = useCallback((payload) = { if (payload.width !== null && payload.height !== null) { console.log('Dimensions:', payload.width, payload.height); } else { console.log('Element unmounted'); } }, []); const { width, height, ref } = useResizeDetector({ onResize, }); return ; }; 使用外部引用(高级)建议不要使用这种方法,因为动态安装和卸载被监视元素可能会导致意外行为。 tsx import { useRef } from 'react'; import { useResizeDetector } from 'react-resize-detector'; const CustomComponent = () = { const targetRef = useRef(null); const { width, height } = useResizeDetector({ targetRef }); return ; }; API 参考…
暂无开放 Issues,或尚未同步最近议题。