繁体   English   中英

如何在滚动上显示React组件

[英]How to reveal a React component on scroll

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

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

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>;
    }
}

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

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));

  }
}

我为同样的需求创建了一个react组件,因为我找不到任何与我需要的匹配的其他实现。 甚至react-headroom也没有给你一些东西,只有在到达页面上的某个点后滚动。

要点在这里: https//gist.github.com/brthornbury/27531e4616b68131e512fc622a61baba

我认为没有理由在这里复制组件代码。 代码主要基于react-headroom代码,但代码较少,因此更简单。

该组件是第一段代码,您可以简单地复制/粘贴然后导入它。 使用导航栏导入代码后,看起来像这样:

class MyScrollInNavBar extends Component {
    render() {
      return (
        <ScrollInNav scrollInHeight={150}>
          <MyNavBar />
        </ScrollInNav>
      );
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM