DE
React - AutoSizer-Komponente
3 points
In diesem Artikel wird gezeigt, wie man in React die aktuelle Größe eines div
-Elements mit hilfe der AutoSizer
-Komponente kontrollieren kann.
Mit AutoSizer
kann man das Ereignis onResize
bearbeiten.
xxxxxxxxxx
1
// Hinweis: Bei der Arbeit mit dem JSX-Compiler soll man die Importzeilen entkommentieren:
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
// Beispiel:
35
36
const App = () => (
37
<div>
38
<h1>Meine Webseite!</h1>
39
<AutoSizer style={{background: '#e1e1e1', width: '400px'}}>
40
{(width, height) => {
41
return (
42
<pre>
43
Container:<br />
44
- Breite: {width}<br />
45
- Höhe: {height}
46
</pre>
47
);
48
}}
49
</AutoSizer>
50
</div>
51
);
52
53
const root = document.querySelector('#root');
54
ReactDOM.render(<App />, root );