【问题标题】: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>
);
}