Next.js:如何从元素中获得应用样式?



我们输入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还是我应该添加一些东西到依赖数组?

代码沙箱在这里

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

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

,然后你可以这样做:

divStyle.getPropertyValue("background-color")

下面是一个示例沙盒(从您的分支)来演示它。