getCompatedStyle 在首页加载时不起作用
我正在使用 React useRef 和 useEffect。本质上,useEffect 检查相关元素是否具有某种样式。如果是这样,那么它就设置了其他东西的状态。当您第一次加载应用程序时,这不起作用,并且我收到错误
'TypeError: Failed toexecute 'getCompulatedStyle' on 'Window':parameter 1 is not of type 'Element'
但是当我刷新时页面,有效吗?有谁能够帮助我理解我做错了什么。
const foodTypeSection = useRef();
const [isFoodTypeSectionVisible, setIsFoodTypeSectionVisible] = useState(true);
useEffect(() => {
const styles = getComputedStyle(foodTypeSection.current);
if (styles.display == 'none') {
setIsFoodTypeSectionVisible(false);
}
}, [foodTypeSection]);
return (
<Section>
<Contained>
<Form ......>
{({ setFieldValue }) => (
<div ref={foodTypeSection}>
<h4>Food</h4>
</div>
)}
</Form>
</Contained>
</Section>
)
I'm making use of React useRef and useEffect. Essentially the useEffect checks if the the element in question has a certain style. If it does, then it set's the state of something else. This doesn't work when you first load the application and I get the error
'TypeError: Failed to execute 'getComputedStyle' on 'Window': parameter 1 is not of type 'Element'
But when I refresh the page, it works? Is anyone able to help me understand what I'm doing wrong.
const foodTypeSection = useRef();
const [isFoodTypeSectionVisible, setIsFoodTypeSectionVisible] = useState(true);
useEffect(() => {
const styles = getComputedStyle(foodTypeSection.current);
if (styles.display == 'none') {
setIsFoodTypeSectionVisible(false);
}
}, [foodTypeSection]);
return (
<Section>
<Contained>
<Form ......>
{({ setFieldValue }) => (
<div ref={foodTypeSection}>
<h4>Food</h4>
</div>
)}
</Form>
</Contained>
</Section>
)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果引用所附加的节点发生更改,效果将不会再次运行,因此即使它有效,它也不会执行您想要的操作。为了让一些代码在每次节点更改时运行,您可以使用回调引用,但即使如此,如果 css 由于某些不相关的原因发生更改,您的代码很可能不会再次运行。
这里的根本问题是,使用 getCompulatedStyle 更改 React 变量是 React 中的反模式。最有可能的是你以一种或另一种方式设置了 css,因此你应该能够确定 div 在 React 中是否可见,而不必询问 DOM。
编辑:
以下是延迟
useEffect
的方法:The effect will not run again if the node that the ref is attached to changes, so even if it worked it wouldn’t do what you want. In order to have some code run everytime a node changes, you can use a callback ref, but even then, your code will most likely not run again if the css changes for some unrelated reason.
The root issue here is that using
getComputedStyle
to change a React variable is an anti-pattern in React. Most likely you're the one setting the css in one way or another, therefore you should be able to determine whether the div is visible inside React, without having to ask the DOM.Edit:
Here is how to delay the
useEffect
: