【问题标题】:Next.js: How to get applied styles from element?Next.js:如何从元素中获取应用样式?
【发布时间】:2021-12-07 05:52:41
【问题描述】:

假设我有 global.css

.test {
  background-color: black;
  width: 50px;
  height: 50px;
}

出于某种原因,我需要从应用元素中获取样式数据。我试过 refs 但它总是返回空字符串。

import { useState, useEffect, useRef } from "react";

const IndexPage = () => {
  const divEl = useRef<HTMLDivElement | null>(null);
  const [divStyle, setDivStyle] = useState({} as CSSStyleDeclaration);

  useEffect(() => {
    if (divEl.current) {
      setDivStyle(divEl.current.style);
    }
  }, [divEl.current]);

  return (
    <div>
      <div ref={divEl} className="test"></div>
      <pre>{JSON.stringify(divStyle, undefined, 2)}</pre>
    </div>
  );
};
export default IndexPage;

是因为 next.js SSR 还是我应该在依赖数组中添加一些东西?

代码沙箱here

【问题讨论】:

  • 问题是你的样式是在那个test类中定义的,但是style属性只返回一个元素的内联样式,也就是style HTML属性中定义的样式.
  • @tromgy 谢谢你的回复。如果我想从元素中获取应用的样式数据怎么办?有可能吗?

标签: reactjs next.js


【解决方案1】:

您可以使用 computed 样式来获得您需要的东西,尽管它不会是一个带有属性的“简单”对象。您需要单独查询每个属性:

if (divEl.current) {
      setDivStyle(getComputedStyle(divEl.current));
    }

然后您可以执行以下操作:

divStyle.getPropertyValue("background-color")

这是一个演示它的example sandbox(来自你的)。

【讨论】:

    猜你喜欢
    • 2022-09-22
    • 1970-01-01
    • 1970-01-01
    • 2020-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    • 1970-01-01
    相关资源
    最近更新 更多