如何在滚动上显示React组件

Wil*_*elm 13 javascript scroll reactjs

我为固定导航创建了一个React组件,我想保持隐藏,直到我滚过页面上的某个点,然后滑入视图.Medium有一个类似于我所描述的标题.

这在jQuery中是一个相对简单的任务,有scrollmagic或waypoint但是有一种惯用的方法用React和vanilla JS完成这个吗?

Kok*_*lav 15

React Way with vanilla JS jsfiddle ;

不要忘记删除EventListener.在此示例中,只有在必要时才会呈现组件

class TopBar extends React.Component {
    state = { isHide: false };

    hideBar = () => {
       const { isHide } = this.state

       window.scrollY > this.prev ?
       !isHide && this.setState({ isHide: true })
       :
       isHide && this.setState({ isHide: false });

       this.prev = window.scrollY;
    }

    componentDidMount(){
        window.addEventListener('scroll', this.hideBar);
    }

    componentWillUnmount(){
         window.removeEventListener('scroll', this.hideBar);
    }

    render(){
        const classHide = this.state.isHide ? 'hide' : '';
        return <div className={`topbar ${classHide}`}>topbar</div>;
    }
}
Run Code Online (Sandbox Code Playgroud)


小智 8

您可以使用诸如react-headroom之类的组件来为您完成繁重的工作.或者,您仍然可以在React中使用路标,在componentDidMount 生命周期方法中设置它并使用它来删除它componentWillUnmount.


Piy*_*oor 0

componentDidMount生命周期挂钩中,执行与您提供的 jQuery 链接中相同的操作:

class Navbar extends React.component {

  let delta = 5;

  render() {
    return (
      <div ref=header></div>
    );
  }

  componentDidMount() {
    $(window).scroll(function(event){
      var st = $(this).scrollTop();

      if(Math.abs(this.state.lastScrollTop - st) <= delta)
        return;

      if (st > lastScrollTop){
        // downscroll code
        // $(this.refs.header).css('visibility','hidden').hover ()
        this.setState({
          navbarVisible: false
        });
      } else {
        // upscroll code
        $(this.refs.header).css('visibility','visible');
        this.setState({
          navbarVisible: true
        });
      }
      lastScrollTop = st;
    }.bind(this));

  }
}
Run Code Online (Sandbox Code Playgroud)

  • 我看到你非常热衷于用 React 帮助其他人,但是你能花点时间来格式化每个答案吗?这不是一场竞赛或数量的游戏,而是质量的游戏。正确格式化代码片段并检查标点符号并不难:) (4认同)