Languages
[Edit]
PL

React - komponent AutoSizer

6 points
Created by:
Palpys
764

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.

// ONLINE-RUNNER:browser;

// Uwaga: Odkomentuj poniższe linijki podczas pracy z kompilatorem JSX:
// import React from 'react';
// import ReactDOM from 'react-dom';

const AutoSizer = React.memo(({ interval, children, ...other }) => {
	const reference = React.useRef();
	const [size, setSize] = React.useState();
	React.useEffect(() => {
      	let storedWidth = size?.width;
      	let storedHeight = size?.height;
      	const id = setInterval(() => {
          	const element = reference.current;
        	if (element) {
              	const width = element.offsetWidth;
                const height = element.offsetHeight;
              	if (width != storedWidth || height != storedHeight) {
                  	storedWidth = width;
                  	storedHeight = height;
                    setSize({ width, height });
                }
            }
        }, interval ?? 100);
      	return () => {
        	clearInterval(id);
        };
	}, [interval]);
	return (
	  <div ref={reference} {...other}>
        {size && children && children(size.width, size.height)}
	  </div>
	);
});

// Przykład:

const App = () => (
  <div>
    <h1>Moja strona!</h1>
    <AutoSizer style={{background: '#e1e1e1', width: '400px'}}>
      {(width, height) => {
      	return (
          <pre>
			Kontener:<br />
			- szerokość: {width}<br />
			- wysokość: {height}
		  </pre>
        );
      }}
    </AutoSizer>
  </div>
);

const root = document.querySelector('#root');
ReactDOM.render(<App />, root );

Alternative titles

  1. React - aktualny rozmiar elementu
  2. React - jak sprawdzić rozmiar elementu
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

ReactJS (PL)

React - komponent AutoSizer
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join