【问题标题】:how to Show or hide Navbar when scroll use react.js?滚动使用react.js时如何显示或隐藏导航栏?
【发布时间】:2023-04-16 01:09:01
【问题描述】:

当我向下滚动并且屏幕下降时,我使用了带有 useState 和 useEffect 的 react.js Hooks 标题在 250 像素后隐藏。现在我想知道当我向上滚动时如何使用 React Hooks 显示 Header。

const Navbar = () => {
  const [show, setShow] = useState(false)
  const controlNavbar = () => {
      if (window.scrollY > 250 ) {
          setShow(true)
      }else{
        setShow(false)
      }
  }

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

和标题:

 <header className={`active ${show && 'hidden'}`}></header>

css:

.active{
    height: 4rem;
    width: 100%;
    position: fixed;
    top: 0px;
    transition: 0.3s linear;
    display: flex;
    justify-content:stretch;
    align-items: center;
    background-color: #FFFFFF;
    border-bottom: 1px solid rgba(0, 0, 0, .1);
    z-index: 40;
    box-shadow: 0 2px 5px -1px rgba(0, 0, 0, .08);
    /* padding: 0 7%; */
}
.hidden{
    height: 4rem;
    width: 100%;
    z-index: 40;
    border-bottom: 1px solid rgba(0, 0, 0, .1);
    box-shadow: 0 2px 5px -1px rgba(0, 0, 0, .08);
    position: fixed;
    top: -80px;
    transition: 0.3s linear;

}

【问题讨论】:

标签: javascript reactjs scroll react-hooks use-state


【解决方案1】:

从这里的几次搜索中,我偶然发现了原始 js 上的滚动功能,但您可以在您的情况下实现它并根据需要调整它,因为目前您的函数只会在 scrollY

在您的 controlNav 函数上创建一个变量,该变量将跟踪您之前滚动的位置/点,然后将其与滚动的当前值进行比较。它将如下所示:

     const controlNavbar = () => {
      if (window.scrollY >= this.lastScroll ) {
          setShow(true)
      }else{
        setShow(false)
      }
    this.lastScroll = window.scrollY;


  }

NB这仅适用于向上滚动和向下滚动,没有最小值..

reference to the raw js

【讨论】: