PL
React - pobierz rozmiar komponentu przed renderowaniem
3 points
W tym artykule przyjrzymy się, jak uzyskać rozmiar komponentu przed renderowaniem.
Uwagi:
W tym przykładzie do uzyskania aktualnego rozmiaru elementu użyjemy funkcji useRef
z atrybutem ref
.
Komponent Container
jest stworzony w oparciu o komponenty funkcyjne.
xxxxxxxxxx
1
// Odkomentuj poniższe linijki podczas pracy z kompilatorem JSX:
2
// import React from 'react';
3
// import ReactDOM from 'react-dom';
4
5
const Container = props => {
6
const reference = React.useRef();
7
const [dimensions, setDimensions] = React.useState({ width: 0, height: 0 });
8
React.useEffect(() => {
9
if (reference.current) {
10
setDimensions({
11
width: reference.current.offsetWidth,
12
height: reference.current.offsetHeight
13
});
14
}
15
}, []);
16
return (
17
<div ref={reference}>
18
<pre>
19
Container:<br />
20
- szerokość: {dimensions.width}<br />
21
- wysokość: {dimensions.height}
22
</pre>
23
</div>
24
);
25
};
26
27
const App = () => (
28
<div style={{background: '#e1e1e1', width: '400px'}}>
29
<h1>Moja strona!</h1>
30
<Container />
31
</div>
32
);
33
34
const root = document.querySelector('#root');
35
ReactDOM.render(<App />, root );
W tym przykładzie atrybut ref
jest używany do pobrania referencji elementu.
Komponent Container
jest stworzony w oparciu o komponenty klasowe.
xxxxxxxxxx
1
// Odkomentuj poniższe linijki podczas pracy z kompilatorem JSX:
2
// import React from 'react';
3
// import ReactDOM from 'react-dom';
4
5
class Container extends React.Component {
6
constructor(props) {
7
super(props);
8
this.state = {
9
dimensions: null
10
};
11
}
12
componentDidMount() {
13
setTimeout(() => this.update());
14
}
15
update() {
16
this.setState({
17
dimensions: {
18
width: this.container.offsetWidth,
19
height: this.container.offsetHeight,
20
}
21
});
22
}
23
render() {
24
const { dimensions } = this.state;
25
return (
26
<div ref={e => (this.container = e)}>
27
<pre>
28
Container:<br />
29
- szerokość: {dimensions && dimensions.width}<br />
30
- wysokość: {dimensions && dimensions.height}
31
</pre>
32
</div>
33
);
34
}
35
}
36
37
const App = () => (
38
<div style={{background: '#e1e1e1', width: '400px'}}>
39
<h1>Moja strona!</h1>
40
<Container />
41
</div>
42
);
43
44
const root = document.querySelector('#root');
45
ReactDOM.render(<App />, root );