Toggle Class based on scroll React JS

后端 未结 7 1799
醉话见心
醉话见心 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:22

    One way to add a scroll listener is to use the componentDidMount() lifecycle method. Following example should give you an idea:

    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 (
          

    Scroll {this.state.isTop ? 'down' : 'up'}!

    ); } } render(, document.getElementById('root'));

    This changes the Text from "Scroll down" to "Scroll up" when your scrollY position is at 100 and above.

    Edit: Should avoid the overkill of updating the state on each scroll. Only update it when the boolean value changes.

提交回复
热议问题