【问题标题】:Detect element reference height change检测元素参考高度变化
【发布时间】:2021-06-29 09:18:26
【问题描述】:

是否可以检测元素引用何时改变它的高度? 我尝试使用以下内容,但是当元素的高度由于某种原因发生变化时,不会检测到变化。 (请考虑这也必须在 IE11 中工作)

useEffect(() => {
  // detect change in reference height
}, [elementRef])

【问题讨论】:

标签: reactjs react-hooks


【解决方案1】:

可能的解决方案是使用 React Refs。试试这个例子作为参考:

export default function Home() {
  const divRef = createRef()
  // ...
  return (
    <div style={{ height: '100vh', width: '100vw' }}>
      <div
        ref={divRef} // ...
      ></div>
    </div>
  )
}

详细代码here.

【讨论】:

  • 不幸的是,执行详细代码的链接导致死循环
【解决方案2】:

我认为你可以在 useEffect 依赖项中使用elementRef.current.clientHeight 来监听标签的高度。

我用这个案例进行了测试,它成功了。

function App() {
  const tag = useRef();
  const [height, setHeight] = useState(10);
  useEffect(() => {
    console.log("updated", tag?.current?.clientHeight);
  }, [tag?.current?.clientHeight]);

  useEffect(() => {
    setInterval(() => {
      setHeight((height) => height + 10);
      console.log(height, tag.current.clientHeight);
    }, 2000);
  }, []);

  return (
    <div className="App" ref={tag}>
      <div style={{ height: height, backgroundColor: "green" }}></div>
    </div>
  );
}

这里是密码箱https://codesandbox.io/embed/reactjs-playground-forked-b8j5n?fontsize=14&hidenavigation=1&theme=dark

【讨论】:

  • 在您的代码中,检测到更改是因为您还更改了组件的状态。否则,它不会触发它。
猜你喜欢
  • 2017-04-01
  • 2016-04-23
  • 2017-04-29
  • 2012-05-31
  • 2016-10-04
  • 1970-01-01
  • 1970-01-01
  • 2015-01-21
  • 1970-01-01
相关资源
最近更新 更多