Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
219 views
in Technique[技术] by (71.8m points)

reactjs - addEventListener on home page only

In the following

import { useEffect } from 'react';
import Link from 'next/link'
import { useRouter } from 'next/router'
import styles from './header.module.scss'

export default function Header(): JSX.Element {
  const router = useRouter()

  const handleClick = (path) => {
    if (path === "/") {
      const header = document.querySelector("header");
      const nav = document.querySelector("nav");
      header.classList.add("headerTest");
      nav.classList.add("menuTest");
      console.log('clicked on home')
    }
    if (path === "/about") {
      const header = document.querySelector("header");
      const nav = document.querySelector("nav")
      header.classList.remove("headerTest");
      nav.classList.remove("menuTest");
      console.log('clicked on about')
    }
  };

  useEffect(() => {
    const header = document.querySelector("header");
    const nav = document.querySelector("nav");
    if (router.pathname === "/") {
      header.classList.add("headerTest");
      nav.classList.add("menuTest");
      const checkScroll = () => {
        if (window.innerWidth <= 768) {
          console.log('scrolling')
          header.classList.remove("headerTest");
          nav.classList.remove("menuTest");
        }
        if (window.scrollY === 0) {
          console.log('top!')
          header.classList.add("headerTest");
          nav.classList.add("menuTest");
        }
      }
      window.addEventListener("scroll", checkScroll);
      // Remove event listener on cleanup
      return () => window.removeEventListener("scroll", checkScroll);
    }
    if (router.pathname !== "/") {
      header.classList.remove("headerTest");
      nav.classList.remove("menuTest");
    }
  }, []);

  return (
    <header className={styles.header}>
      <h1>
        <Link href='/'><a onClick={() => handleClick("/")}><span className='offscreen'>Home page</span></a></Link>
      </h1>
      <nav id="menu" className={styles.menu}>
        <ul>
          <li>
            <Link href='/mvg'>
              <a onClick={() => handleClick("/about")}>MVG</a>
            </Link>
          </li>
        </ul>
      </nav>
    </header>
  )
}

I only want to use addEventListener and active my checkScroll function on my homepage. But because router.pathname === '/' whenever I click on the about page (since I'm still ON the homepage when I click the about page), the checkScroll function is still activated in my About Page.

How do I get around this? I've tried using state, localStorage, and all sorts of fancy tricks and couldn't find a solution.

Edit*

The Header is being used in _app.tsx as follows

import { AppProps } from 'next/app'
import '../styles/globals.scss'
import Head from 'next/head'
import Header from '../components/header/header'
import Footer from '../components/footer/footer'

export default function App({ Component, pageProps }: AppProps) {
  return (
    <>
    <Head>
    </Head>
    <div id='wrap'>
      <Header/>
      <Component {...pageProps} />
      <Footer />
    </div>
  </>
  )
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Here is the sample code.

const checkScroll = () => {
    if (window.innerWidth <= 768) {
      console.log('scrolling')
      header.classList.remove("headerTest");
      nav.classList.remove("menuTest");
    }
    if (window.scrollY === 0) {
      console.log('top!')
      header.classList.add("headerTest");
      nav.classList.add("menuTest");
    }
  }
  
  useEffect(() => {
    const header = document.querySelector("header");
    const nav = document.querySelector("nav");
    if (router.pathname === "/") {
      header.classList.add("headerTest");
      nav.classList.add("menuTest");
      
      window.addEventListener("scroll", checkScroll);
      // Remove event listener on cleanup
     
    }
    if (router.pathname !== "/") {
      header.classList.remove("headerTest");
      nav.classList.remove("menuTest");
      window.removeEventListener("resize", checkScroll);
    }
   return () => window.removeEventListener("resize", checkScroll);
  }, [router.pathname]);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...