document.body.classList.add/remove not working as expected

huangapple go评论72阅读模式
英文:

document.body.classList.add/remove not working as expected

问题

当我调用add(<某个类名>)时,它只会将类属性添加到body元素,但不会附加任何值。与此同时,如果我手动将类添加到body元素,然后调用remove(),什么也不会发生。

这是当前的代码。我预期在组件首次渲染时将类overflow-hidden添加到body元素,同时在组件关闭时将类overflow-hiddenbody元素中移除。

英文:

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(() =&gt; {
        document.body.classList.add(&#39;overflow-hidden&#39;)

        return (
            document.body.classList.remove(&#39;overflow-hidden&#39;)
        )
    }, [])

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(() =&gt; {
    document.body.classList.add(&quot;overflow-hidden&quot;);
    return () =&gt; {
      document.body.classList.remove(&quot;overflow-hidden&quot;);
    };
  }, []);

huangapple
  • 本文由 发表于 2023年2月27日 08:34:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/75575914.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定