如何通过React中的ref获取元素样式

问题描述 投票:1回答:1

如果使用CSS将<div className="scale" ref={ref}>的高度设置为400像素,我希望ref.current.clientHeight为400像素,但始终为19。

我如何获得div的高度?

我的计划是将其设置为100%,但仍然知道div的高度。

.scale {
   height: 400px;
   display: block;
}
import React, { useState, useLayoutEffect, useRef } from "react";

function Scale() {
  const [height, setHeight] = useState(0);
  const ref = useRef<HTMLDivElement>(null);

  useLayoutEffect(() => {
    if (ref.current && ref.current.clientHeight) {
      setHeight(ref.current.clientHeight);
    }
  });
  return (
    <div className="scale" ref={ref}>
      {height}
    </div>
  );
}

export { Scale };
javascript css reactjs typescript ref
1个回答
0
投票
window.getComputedStyle(ref.current)
© www.soinside.com 2019 - 2024. All rights reserved.