首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用参考值和高度

使用参考值和高度
EN

Stack Overflow用户
提问于 2022-02-16 11:48:39
回答 1查看 287关注 0票数 0

我想知道如何在加载时获得useRef的宽度和高度,以及何时变化。

我正试图将组件的确切尺寸传递给它的子部件。

MapContainer.js

代码语言:javascript
复制
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

代码语言:javascript
复制
<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>

但是,当父级宽度发生变化时,我所采用的方法并不是获得宽度和高度。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-02-16 12:30:45

若要在调整大小后获得新的宽度和高度,需要侦听窗口的调整大小事件,例如:

代码语言:javascript
复制
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>
  );
};
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71141308

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档