反应:无法读取 document.body.style.marginRight
React: cannot read document.body.style.marginRight
我无法阅读正文的右边距 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 仅 returns 内联样式。要从 css 文件访问样式,您应该使用:
window.getComputedStyle(document.body).marginRight
我无法阅读正文的右边距 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 仅 returns 内联样式。要从 css 文件访问样式,您应该使用:
window.getComputedStyle(document.body).marginRight