【发布时间】: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属性只返回一个元素的内联样式,也就是styleHTML属性中定义的样式. -
@tromgy 谢谢你的回复。如果我想从元素中获取应用的样式数据怎么办?有可能吗?