【问题标题】:How to add a classname in React Js?如何在 React Js 中添加类名?
【发布时间】:2021-11-30 18:05:18
【问题描述】:

当用户向下滚动时,我试图向导航栏添加一个类名。我这样做了:

var myNav = document.getElementById("nav");

window.onscroll = function() {
  "use strict";
  if (document.body.scrollTop >= 150 || document.documentElement.scrollTop >= 150) {
    myNav.classList.add("scroll");
  } else {
    myNav.classList.remove("scroll");
  }
};

但它给了我一个错误:

Cannot read properties of null (reading 'classList')

我不知道为什么:(

【问题讨论】:

    标签: javascript reactjs react-native


    【解决方案1】:

    您收到该错误是因为不存在具有该 ID 的元素。也许它不存在,或者它永远不存在。但无论哪种方式,我建议您避免将 react 与直接操作 dom 混合使用。这样做的反应方式是在 useEffect 中监听滚动,然后设置状态:

    const NavBar = () => {
      const [scroll, setScroll] = useState(false);
      useEffect(() => {
        const handleScroll = () => {
          setScroll(document.body.scrollTop >= 150 || document.documentElement.scrollTop >= 150);
        }
        window.addEventListener('scroll', handleScroll);
        return () => {
          window.removeEventListener('scroll', handleScroll);
        }
      }, []);
    
      return (
        <div id="nav" className={scroll ? "scroll" : undefined}>
    
        </div>
      );
    }
    

    【讨论】:

    • 非常感谢!效果很好!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-27
    • 2018-10-20
    • 2020-08-06
    • 2022-11-07
    • 1970-01-01
    • 1970-01-01
    • 2022-06-12
    相关资源
    最近更新 更多