我想知道如何在加载时获得useRef的宽度和高度,以及何时变化。
我正试图将组件的确切尺寸传递给它的子部件。
MapContainer.js
const mapComponent = useRef(null);
const [mapWidth, setMapWidth] = useState(0);
const [mapHeight, setMapHeight] = useState(0);
useEffect(() => {
if (mapComponent.current !== null) {
setMapWidth(mapComponent.current.clientWidth);
setMapHeight(mapComponent.current.clientHeight);
}
}, [mapComponent]);
<div className={`bg-white rounded-[32px] overflow-hidden relative`} ref={mapComponent}>
<Map
style="mapbox://styles/ayagoumi/ckyvm0dx5001714mplg2y1oz7"
zoom={zoom}
center={position}
movingMethod="easeTo"
containerStyle={{
height: `${mapHeight}px`, // this is what i want to change
width: `${mapWidth}px`, // this is what i want to change
borderRadius: "32px",
zIndex: "0",
overflow: "hidden",
}}
>
</Map>
</div>Index.js
<section className="flex flex-wrap justify-between w-full gap-4 xl:flex-nowrap">
<div></div>
<div className="flex flex-col order-2 gap-4 sm:flex-row grow">
<MapContainer styles="w-full md:!w-[50%] lg:w-full min-w-[300px] min-h-[300px] order-2 rounded-[32px] overflow-hidden"></MapContainer>
</div>
</section>但是,当父级宽度发生变化时,我所采用的方法并不是获得宽度和高度。
发布于 2022-02-16 12:30:45
若要在调整大小后获得新的宽度和高度,需要侦听窗口的调整大小事件,例如:
const Map = () => {
const mapComponent = useRef(null);
const [mapWidth, setMapWidth] = useState(0);
const [mapHeight, setMapHeight] = useState(0);
const onResize = () => {
const rect = mapComponent.current.getBoundingClientRect();
if (rect) {
setMapWidth(rect.width);
setMapHeight(rect.height);
}
};
useEffect(() => {
onResize();
window.addEventListener('resize', onResize);
}, []);
return (
<div ref={mapComponent}>
<Child width={mapWidth} height={mapHeight}>A</Child>
<Child width={mapWidth} height={mapHeight}>B</Child>
<Child width={mapWidth} height={mapHeight}>C</Child>
<Child width={mapWidth} height={mapHeight}>D</Child>
</div>
);
};https://stackoverflow.com/questions/71141308
复制相似问题