我无法读取正文的 margin-right css 属性。它似乎在初始渲染时失败了,但有几次当我手动设置 margin-right 时它似乎起作用了。我希望它在组件渲染时有所作为。尝试了 useEffect 和 useLayoutEffect 没有成功。
相关的 CSS:
body {
margin-right: 10px;
}
简单的 create-react-app:
function App() {
const [marginRight, setmarginRight] = useState(
document.body.style.marginRight
);
return (
<div className="App">
<p>BODY Right margin is: {marginRight}</p>
</div>
);
}
最佳答案
HTMLelement.style 只返回内联样式。要从您的 css 文件访问样式,您应该使用:
window.getComputedStyle(document.body).marginRight
关于css - react : cannot read document. body.style.marginRight,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54499339/