更改容器元素的宽度或高度时,我的组件必须更新一些值。我发现有两种方法可以监视此尺寸,但是它们都有局限性:
我的组件看起来像:
const MyComponent = props => {
const containerRef = useRef();
const [ dimensions, setDimensions ] = useState({width: 0, height: 0});
/**
* Watch for element dimensions changes
*/
const checkContainerSizes = () => {
const newWidth = !!containerRef.current ? containerRef.current.offsetWidth || 0 : 0;
const newHeight = !!containerRef.current ? containerRef.current.offsetHeight || 0 : 0;
if( dimensions.width !== newWidth || dimensions.height !== newHeight ) {
setDimensions({
width: newWidth,
height: newHeight
});
return true;
} else {
return false;
}
}
useEffect( () => {
if( ResizeObserver in window ) return;
let unmounted = false;
const requestCheck = () => {
window.requestAnimationFrame( () => {
if( unmounted ) return;
if( !checkContainerSizes() ) {
requestCheck();
}
});
}
requestCheck();
return () => unmounted = true;
});
useEffect( () => {
if( ResizeObserver in window ) {
const resizeObserver = new ResizeObserver(entries => {
checkContainerSizes();
});
resizeObserver.observe(containerRef.current);
return () => resizeObserver.disconnect();
}
}, []);
/**
* Update svg element depend on container dimensions
*/
useEffect( () => {
// Update actions
}, [dimensions]);
return (
<div ref={containerRef}>
</div>
);
}
问题:是否有更优雅的方法来监视特定元素的调整大小事件?