如何在 React.js 中动态跟踪 div 的宽度/高度

Ada*_*ess 3 css resize reactjs

我的工作任务需要帮助:我有一些具有以下样式的div块:

.main-div {
  width: 500px;
  height: 400px;
  border: 1px solid #000;
  resize: both;
  overflow: hidden;
}
Run Code Online (Sandbox Code Playgroud)

还有一些 React 组件:

import React, { useState } from "react";

export const SomeComponent = () => {
  const [width, setWidth] = useState();
  const [height, setHeight] = useState();

  return (
    <div className="main-div">
     <p>Block width: {width}, height: {height} </p>
    </div>
  )
}
Run Code Online (Sandbox Code Playgroud)

如何动态获取调整div大小的宽度/高度?我的意思是我必须在调整大小的过程中跟踪块尺寸。

小智 15

您可以组合ResizeObserveruseEffectuseRef

  • ResizeObserver允许您观察 HTML 元素并在每次调整大小时执行事件处理程序;
  • useEffect在组件安装后立即执行,因此这是将观察者附加到 div 的正确位置,并在组件将通过返回的函数卸载时断开连接;
  • useRef创建对子级的引用。
import React, { useState, useEffect, useRef } from "react";

export const SomeComponent = () => {
  const [width, setWidth] = useState();
  const [height, setHeight] = useState();

  // useRef allows us to "store" the div in a constant, 
  // and to access it via observedDiv.current
  const observedDiv = useRef(null);

  useEffect(() => {
    if (!observedDiv.current) {
      // we do not initialize the observer unless the ref has
      // been assigned
      return;
    }

    // we also instantiate the resizeObserver and we pass
    // the event handler to the constructor
    const resizeObserver = new ResizeObserver(() => {
      if(observedDiv.current.offsetWidth !== width) {
        setWidth(observedDiv.current.offsetWidth); 
      }
      if(observedDiv.current.offsetHeight !== height) {
        setHeight(observedDiv.current.offsetHeight);
      }
    });
    
    // the code in useEffect will be executed when the component
    // has mounted, so we are certain observedDiv.current will contain
    // the div we want to observe
    resizeObserver.observe(observedDiv.current);


    // if useEffect returns a function, it is called right before the
    // component unmounts, so it is the right place to stop observing
    // the div
    return function cleanup() {
      resizeObserver.disconnect();
    }
  },
  // only update the effect if the ref element changed
  [observedDiv.current])

  return (
    <div className="main-div" ref={observedDiv}>
     <p>Block width: {width}, height: {height} </p>
    </div>
  )
}
Run Code Online (Sandbox Code Playgroud)

来源

  1. 调整观察者大小:
  2. useEffect 钩子
  3. useRef 钩子

  • @AdamBess而不是评论,你应该接受答案! (2认同)