基于 scroll React JS 的 Toggle 类

新手上路,请多包涵

我正在使用 bootstrap 4 导航栏,想在 ig 400px 向下滚动后更改背景颜色。我正在查看反应文档并找到了一个 onScroll 但找不到那么多信息。到目前为止我有…

我不知道我是否使用了正确的事件侦听器或如何设置高度等。

而且我并没有真正设置内联样式……

   import React, { Component } from 'react';

   class App extends Component {

   constructor(props) {
    super(props);

      this.state = {  scrollBackground: 'nav-bg' };
      this.handleScroll = this.handleScroll.bind(this);
   }

   handleScroll(){
      this.setState ({
         scrollBackground: !this.state.scrollBackground
       })
    }

 render() {
 const scrollBg = this.scrollBackground ? 'nav-bg scrolling' : 'nav-bg';

 return (
   <div>

       <Navbar inverse toggleable className={this.state.scrollBackground}
                                  onScroll={this.handleScroll}>
        ...
      </Navbar>

    </div>
   );
  }
}

export default App;

原文由 Fernando B 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 346
2 个回答

添加滚动侦听器的一种方法是使用 componentDidMount() 生命周期方法。下面的例子应该给你一个想法:

 import React from 'react';
import { render } from 'react-dom';

class App extends React.Component {
  state = {
    isTop: true,
  };

  componentDidMount() {
    document.addEventListener('scroll', () => {
      const isTop = window.scrollY < 100;
      if (isTop !== this.state.isTop) {
          this.setState({ isTop })
      }
    });
  }
  render() {
    return (
      <div style={{ height: '200vh' }}>
        <h2 style={{ position: 'fixed', top: 0 }}>Scroll {this.state.isTop ? 'down' : 'up'}!</h2>
      </div>
    );
  }
}

render(<App />, document.getElementById('root'));

当您的 scrollY 位置在 100 及以上时,这会将文本从“向下滚动”更改为“向上滚动”。

编辑:应该避免在每个滚动条上更新状态的矫枉过正。仅在布尔值更改时更新它。

原文由 glennreyes 发布,翻译遵循 CC BY-SA 4.0 许可协议

对于那些 在 2020 年之后阅读此问题 的人,我采用了@glennreyes 的回答并使用 React Hooks 重写了它:

   const [scroll, setScroll] = useState(0)

  useEffect(() => {
    document.addEventListener("scroll", () => {
      const scrollCheck = window.scrollY < 100
      if (scrollCheck !== scroll) {
        setScroll(scrollCheck)
      }
    })
  })

请记住, useState 有一个包含两个元素的数组,第一个是 状态对象,第二个 是更新它的函数

顺带一提, useEffect 帮助我们替换了 componentDidmount ,为了简洁起见,当前编写的函数不做任何清理。

如果您发现清理很有必要,您可以在 useEffect 中返回一个函数。

您可以 在这里 全面阅读。

更新:

如果你们想要将其 模块化 甚至进行 清理,您可以这样做:

  1. 如下创建 自定义挂钩
    import { useState, useEffect } from "react"

   export const useScrollHandler = () => {
   // setting initial value to true
   const [scroll, setScroll] = useState(1)

   // running on mount
   useEffect(() => {
     const onScroll = () => {
       const scrollCheck = window.scrollY < 10
       if (scrollCheck !== scroll) {
         setScroll(scrollCheck)
       }
     }

   // setting the event handler from web API
   document.addEventListener("scroll", onScroll)

   // cleaning up from the web API
    return () => {
      document.removeEventListener("scroll", onScroll)
     }
   }, [scroll, setScroll])

   return scroll

   }

  1. 在您认为合适的 任何组件中调用它
    const component = () => {

   // calling our custom hook
   const scroll = useScrollHandler()

   ....... rest of your code

   }

原文由 Pouya Ataei 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题