如何修复Nextjs中的“未定义窗口”

时间:2020-10-04 12:59:45

标签: node.js reactjs next.js

Hi试图在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

1 个答案:

答案 0 :(得分:1)

窗口在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
}
}, [])