Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

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

reactjs - React, how to show sticky nav when scrolling

I have a demo here

It's a simple react page with a header, nav and text content.

I'm trying to show the nav and then have it fixed at the top od the page when the page scrolls past the red header.

So I don't want it to showe when the page loads put then display it when the page scrolls past the res header.

I'm trying to use useEffect but I need to get a boolean some how to wrap the <Nav />

const [scrollPosition, setScrollPosition] = useState(0)
const [sticky, setSticky] = useState(false)

const handleScroll = () => {
  const position = window.pageYOffset
  setScrollPosition(position)
}

useEffect(() => {
  window.addEventListener('scroll', handleScroll, { passive: true })

  scrollPosition > 20 ? 'navShow' : 'navHide'

  return () => {
      window.removeEventListener('scroll', handleScroll)
  }
}, [])

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

1 Answer

0 votes
by (71.8m points)
等待大神答复

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