Toggle Class based on scroll React JS

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

    It's Better

    import React from 'react';
    import { render } from 'react-dom';
    
    class App extends React.Component {
        constructor(props) {
        super(props);
    
        this.state = {
          isTop: true
        };
        this.onScroll = this.onScroll.bind(this);
      }
    
      componentDidMount() {
        document.addEventListener('scroll', () => {
          const isTop = window.scrollY < 100;
          if (isTop !== this.state.isTop) {
            this.onScroll(isTop);
          }
        });
      }
    
      onScroll(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'));
    
    0 讨论(0)
提交回复
热议问题