Toggle Class based on scroll React JS

后端 未结 7 1876
醉话见心
醉话见心 2021-02-01 06:38

I\'m using bootstrap 4 nav bar and would like to change the background color after ig 400px down scroll down. I was looking at the react docs and found a onScroll but couldn\'t

7条回答
  •  野性不改
    2021-02-01 07:25

    These are two hooks - one for direction (up/down/none) and one for the actual position

    Use like this:

    useScrollPosition(position => {
        console.log(position)
      })
    
    useScrollDirection(direction => {
        console.log(direction)
      })
    

    Here are the hooks:

    import { useState, useEffect } from "react"
    
    export const SCROLL_DIRECTION_DOWN = "SCROLL_DIRECTION_DOWN"
    export const SCROLL_DIRECTION_UP = "SCROLL_DIRECTION_UP"
    export const SCROLL_DIRECTION_NONE = "SCROLL_DIRECTION_NONE"
    
    export const useScrollDirection = callback => {
      const [lastYPosition, setLastYPosition] = useState(window.pageYOffset)
      const [timer, setTimer] = useState(null)
    
      const handleScroll = () => {
        if (timer !== null) {
          clearTimeout(timer)
        }
        setTimer(
          setTimeout(function () {
            callback(SCROLL_DIRECTION_NONE)
          }, 150)
        )
        if (window.pageYOffset === lastYPosition) return SCROLL_DIRECTION_NONE
    
        const direction = (() => {
          return lastYPosition < window.pageYOffset
            ? SCROLL_DIRECTION_DOWN
            : SCROLL_DIRECTION_UP
        })()
    
        callback(direction)
        setLastYPosition(window.pageYOffset)
      }
    
      useEffect(() => {
        window.addEventListener("scroll", handleScroll)
        return () => window.removeEventListener("scroll", handleScroll)
      })
    }
    
    export const useScrollPosition = callback => {
      const handleScroll = () => {
        callback(window.pageYOffset)
      }
    
      useEffect(() => {
        window.addEventListener("scroll", handleScroll)
        return () => window.removeEventListener("scroll", handleScroll)
      })
    }
    

提交回复
热议问题