PL
React - komponent AutoSizer
6 points
W tym artykule, chcielibyśmy pokazać, jak w React-cie monitorować aktualny rozmiar elementu div
za pomocą komponentu AutoSizer
.
AutoSizer
pozwala obsłużyć wydarzenie onResize
.
xxxxxxxxxx
1
// Uwaga: Odkomentuj poniższe linijki podczas pracy z kompilatorem JSX:
2
// import React from 'react';
3
// import ReactDOM from 'react-dom';
4
5
const AutoSizer = React.memo(({ interval, children, other }) => {
6
const reference = React.useRef();
7
const [size, setSize] = React.useState();
8
React.useEffect(() => {
9
let storedWidth = size?.width;
10
let storedHeight = size?.height;
11
const id = setInterval(() => {
12
const element = reference.current;
13
if (element) {
14
const width = element.offsetWidth;
15
const height = element.offsetHeight;
16
if (width != storedWidth || height != storedHeight) {
17
storedWidth = width;
18
storedHeight = height;
19
setSize({ width, height });
20
}
21
}
22
}, interval ?? 100);
23
return () => {
24
clearInterval(id);
25
};
26
}, [interval]);
27
return (
28
<div ref={reference} {other}>
29
{size && children && children(size.width, size.height)}
30
</div>
31
);
32
});
33
34
// Przykład:
35
36
const App = () => (
37
<div>
38
<h1>Moja strona!</h1>
39
<AutoSizer style={{background: '#e1e1e1', width: '400px'}}>
40
{(width, height) => {
41
return (
42
<pre>
43
Kontener:<br />
44
- szerokość: {width}<br />
45
- wysokość: {height}
46
</pre>
47
);
48
}}
49
</AutoSizer>
50
</div>
51
);
52
53
const root = document.querySelector('#root');
54
ReactDOM.render(<App />, root );