![](/img/trans.png)
[英]How to fix "ReferenceError: Blob is not defined" in NextJs?
[英]How to fix "window is not defined" in Nextjs
嗨,试图在 NextJS 应用程序中创建一个像 [this][1] 的组件,但它显示错误ReferenceError: window is not defined
//Navbar,js
import styles from "../styles/Navbar.module.css";
export default function Navbar() {
window.onscroll = function () {
scrollFunction();
};
function scrollFunction() {
if (
document.body.scrollTop > 20 ||
document.documentElement.scrollTop > 20
) {
document.getElementById("navbar").style.top = "0";
} else {
document.getElementById("navbar").style.top = "-50px";
}
}
return (
<div id="navbar">
<a href="#">Home</a>
<a href="#">About</a>
<a href="#">Blog</a>
<a href="#">Contact</a>
</div>
);
}
任何人都可以帮忙吗? 我刚刚开始节点 [1]: https : //www.w3schools.com/howto/howto_js_navbar_slide.asp
ssr 上的窗口未定义。 将此函数放在 useEffect 块中,useEffect 在 ssr 期间不运行。
useEffect(()=> {
window.onscroll = function () {
scrollFunction();
};
function scrollFunction() {
if (
document.body.scrollTop > 20 ||
document.documentElement.scrollTop > 20
) {
document.getElementById("navbar").style.top = "0";
} else {
document.getElementById("navbar").style.top = "-50px";
}
}
return ()=> {
//remove the event listener
}
}, [])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.