英文:
document.body.classList.add/remove not working as expected
问题
当我调用add(<某个类名>)
时,它只会将类属性添加到body
元素,但不会附加任何值。与此同时,如果我手动将类添加到body
元素,然后调用remove()
,什么也不会发生。
这是当前的代码。我预期在组件首次渲染时将类overflow-hidden
添加到body
元素,同时在组件关闭时将类overflow-hidden
从body
元素中移除。
英文:
document.body.classList.add/remove not working as expected
When I call add(<some class name>), it only adds the class attribute to the body element, but it doesn't attach any value to it. Meanwhile, if I manually add the class to the body element and then call remove(), nothing happens
useEffect(() => {
document.body.classList.add('overflow-hidden')
return (
document.body.classList.remove('overflow-hidden')
)
}, [])
This is the code currently. I expected the class 'overflow-hidden' to be added to the body element when the component is first rendered and I expected the class 'overflow-hidden' to be removed from the body element was the component was closed
答案1
得分: 0
我认为你对return
有问题。它必须返回一个函数,而这个函数将在组件卸载时被调用:
useEffect(() => {
document.body.classList.add("overflow-hidden");
return () => {
document.body.classList.remove("overflow-hidden");
};
}, []);
英文:
I think you have issue with the return
. it has to return a function and this function will be called when the component is unmounted:
useEffect(() => {
document.body.classList.add("overflow-hidden");
return () => {
document.body.classList.remove("overflow-hidden");
};
}, []);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论