简体   繁体   中英

ReactJS - Change navbar color on scroll

I have the following code:

import React, {useState} from 'React';
import Header from './styles.js';

const HeaderComponent = props => 
{
  const [navBg, setNavBg] = useState(false);
  const isHome = props.name === 'Homepage' ? true : false;

  const changeNavBg = () =>
  {
   window.scrollY >= 800 ? setNavBg(true) : setNavBg(false);
  }

  window.addEventListener('scroll', changeNavBg);

  return (
  <Header {...(isHome && navBg ? { backgroundColor: '#00008' : {})} />
  )
}

What I am trying to achieve is that when scrolling past 800px, I want my Header to change colors.

Cheers for your time.

Here's a couple of approaches you could try

1. Use the React onScroll UI event
 return (
   <div onScroll={changeNavBg}>
     <Header {...(isHome && navBg ? { backgroundColor: '#00008' : {})} />
   </div>
 )
2. Consider binding the listener to a useEffect
import React, {useState} from 'React';
import Header from './styles.js';

const HeaderComponent = props => {
  const [navBg, setNavBg] = useState(false);
  const isHome = props.name === 'Homepage' ? true : false;

  const changeNavBg = () => {
   window.scrollY >= 800 ? setNavBg(true) : setNavBg(false);
  }

  useEffect(() => {
    window.addEventListener('scroll', changeNavBg);
    return () => {
      window.removeEventListener('scroll', changeNavBg);
    }
  }, [])

  return (
  <Header {...(isHome && navBg ? { backgroundColor: '#00008' : {})} />
  )
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM