FezVrasta/react-resize-aware
关于
⇲👁 一个简单的 React Hook,可在任意目标元素尺寸发生变化时监听其 resize 事件
网站与应用开发实测星标增长
- 24小时
- 0
- 7天
- 0
- 15天
- 0
- 1个月
- 正在收集历史
各周期内的星标净变化,周期相互重叠,并非每日新增。缺失的测量保持空白。星标代表关注度,不代表软件质量。
README.md
原文react-resize-aware
It does one thing, it does it well: listens to resize events on any HTML element.
react-resize-aware is a zero dependency, ~600 bytes React Hook you can use to detect resize events without relying on intervals, loops, DOM manipulation detection or CSS redraws.
It takes advantage of the resize event on the HTMLObjectElement, works on any browser I know of, and it's super lightweight.
In addition, it doesn't directly alters the DOM, everything is handled by React.
Looking for the 2.0 docs? Click here
Installation
yarn add react-resize-aware
or with npm:
npm install --save react-resize-aware
Usage
The API is simple yet powerful, the useResizeAware Hook
returns a React node you will place inside the measured element, and an object containing its sizes:
import React from "react";
import useResizeAware from "react-resize-aware";
const App = () => {
const [resizeListener, sizes] = useResizeAware();
return (
<div style={{ position: "relative" }}>
{resizeListener}
Your content here. (div sizes are {sizes?.width} x {sizes?.height})
</div>
);
};
Heads up!: Make sure to assign a
position != initialto the HTMLElement you want to target (relative,absolute, orfixedwill work).
API
The Hook returns an array with two elements inside:
[resizeListener, ...] (first element)
This is an invisible React node that must be placed as direct-child of the HTMLElement you want to listen the resize events of.
The node is not going to interfer with your layouts, I promise.
[..., sizes] (second element)
This object contains the width and height properties, it could be null if the element is not yet rendered.
Custom reporter
You can customize the properties of the sizes object by passing a custom reporter function as first argument of useResizeAware.
const customReporter = (target: ?HTMLIFrameElement) => ({
clientWidth: target != null ? target.clientWidth : 0,
});
const [resizeListener, sizes] = useResizeAware(customReporter);
return (
<div style={{ position: "relative" }}>
{resizeListener}
Your content here. (div clientWidth is {sizes.clientWidth})
</div>
);
The above example will report the clientWidth rather than the default offsetWidth and offsetHeight.
React to size variations
For completeness, below you can find an example to show how to make your code react to size variations using React Hooks:
const App = () => {
const [resizeListener, sizes] = useResizeAware();
React.useEffect(() => {
console.log("Do something with the new size values");
}, [sizes.width, sizes.height]);
return (
<div style={{ position: "relative" }}>
{resizeListener}
Your content here.
</div>
);
};
探索相关项目
加载中…