所以我想在 React 中为我的网站制作一个粘性导航栏,我有一些 javascript 代码,当我运行它时,我收到一条错误消息 TypeError: Cannot read property 'remove' of undefined
当我执行 Console.log(nav)
时,它说它已定义,但是当我执行 console.log(sticky)
时,它说它未定义,这就是为什么我收到错误,因为我试图对未定义的内容运行 remove
。
import React from "react"
import {Link} from "react-router-dom"
import './App.css';
export default function App (){
const navStyle = {
color: "white"
};
// When the user scrolls the page, execute myFunction
window.onscroll = function() {myFunction()};
// Get the navbar
var nav = document.getElementsByClassName("nav");
console.log(nav)
// Get the offset position of the navbar
var sticky = nav.offsetTop;
console.log(sticky)
// Add the sticky class to the navbar when you reach its scroll position. Remove "sticky" when you leave the scroll position
function myFunction() {
if (window.pageYOffset >= sticky) {
nav.classList.add("sticky")
} else {
nav.classList.remove("sticky");
}
}
return (
<div className="App-header">
<nav className="nav">
<h3>Logo</h3>
<ul>
<Link style={navStyle} to="/">
<li>Home</li>
</Link>
<Link style={navStyle} to="LogIn">
<li>Log In</li>
</Link>
</ul>
</nav>
</div>
)
}
错误表明问题出在nav.classList.remove("sticky")线上
如有任何帮助,我们将不胜感激。
谢谢
最佳答案
错误在于您 getElementsByClassName
返回元素列表。您只需要获取第一个元素。但这不是使用 react 钩子(Hook)执行此操作的正确方法。您应该使用 useRef
和 useEffect
Hook
import React from "react"
import {Link} from "react-router-dom"
import './App.css';
export default function App (){
const navStyle = {
color: "white"
};
const navRef= useRef(null);
useEffect(() => {
window.addEventListener('scroll', myFunction);
() => { window.removeEventListener('scroll', myFunction) }
}, [])
// Add the sticky class to the navbar when you reach its scroll position. Remove "sticky" when you leave the scroll position
function myFunction() {
var nav = navRef.current
console.log(nav)
// Get the offset position of the navbar
var sticky = nav.offsetTop;
console.log(sticky)
if (window.pageYOffset >= sticky) {
nav.classList.add("sticky")
} else {
nav.classList.remove("sticky");
}
}
return (
<div className="App-header">
<nav ref={navRef} className="nav">
<h3>Logo</h3>
<ul>
<Link style={navStyle} to="/">
<li>Home</li>
</Link>
<Link style={navStyle} to="LogIn">
<li>Log In</li>
</Link>
</ul>
</nav>
</div>
)
}
关于javascript - ReactJS 中 undefined variable ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65879274/