React - Slide fixed navbar up on scroll down and slide down on scroll up

半城伤御伤魂 提交于 2019-12-04 15:51:53

You shouldn't use refs as a solution to register event listeners or adding/removing classes. As you suggested, you should use component lifecycle hooks to begin (and stop) listening for scrolls on the window.

export default class App extends Component {
  state = { hidden: false };

  constructor(props) {
    super(props);

    // Bind the function to this component, so it has access to this.state
    this.handleScroll = this.handleScroll.bind(this);
  }

  componentWillMount() {
    // When this component mounts, begin listening for scroll changes
    window.addEventListener('scroll', this.handleScroll);
  }

  componentWillUnmount() {
    // If this component is unmounted, stop listening
    window.removeEventListener('scroll', this.handleScroll);
  }

  handleScroll(e) {
    let lastScrollTop = 0;
    const currentScrollTop = navbar.scrollTop;

    // Set the state of hidden depending on scroll position
    // We only change the state if it needs to be changed
    if (!this.state.hidden && currentScrollTop > lastScrollTop) {
      this.setState({ hidden: true });
    } else if(this.state.hidden) {
      this.setState({ hidden: false });
    }
    lastScrollTop = currentScrollTop;
  }

  render() {
    // We pass a hidden prop to Navbar which can render className="hidden" if the prop is true
    return (
      <Navbar hidden={this.state.hidden} />
    );
  }
}

Also, looking at the scroll function you provided, it won't work, as lastScrollTop will always be 0. If you're looking for a scroll solution take a look at this answer as it has a similar solution to what your fixed navbar would need (except, hiding instead of being shown) : Sticky Header after scrolling down

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!