简体   繁体   English

仅在用户开始向下滚动后如何显示标题? [反应]

[英]How to display a header only after the user starts to scroll down? [React]

I'm using react, and I would like to display a header only after the user has scrolled down 150px on the page. 我正在使用react,并且仅在用户在页面上向下滚动150px后才显示标题。

So when the user starts to scroll down, I would like a sticky header to appear. 因此,当用户开始向下滚动时,我希望出现一个粘性标题。 And again, when the user scrolls to the top of the page, the sticky header disappears. 再次,当用户滚动到页面顶部时,粘性标题消失。

<div className="container">
    // display this on top of the page:
    <JumbotronImage />
    // display this when user starts to scroll, sticky on top of the page
    <StickyHeader />
</div> 

I tried to do it with window.addEventListener('scroll'... , and I also tried https://github.com/fisshy/react-scroll but couldn't get it to work yet. Any suggestions? 我试图用window.addEventListener('scroll'...来做到这一点,我也尝试了https://github.com/fisshy/react-scroll,但是还不能使它工作。有什么建议吗?

I can think upon that your code would look as following. 我可以认为您的代码如下所示。 And the solution should fit like this. 解决方案应该像这样。

export class App extends React.Component {
 componentDidMount() {
   ReactDOM.findDOMNode(this.stickyHeader).addEventListener('scroll', this.handleScroll.bind(this));
 }
 componentWillUnmount() {
   ReactDOM.findDOMNode(this.stickyHeader).removeEventListener('scroll', this.handleScroll.bind(this));
 }
 handleScroll() {
   // Add the logic here
 }
 render() {
   const {props} = this;

   return (
     <div className="container">
        // display this on top of the page:
        <JumbotronImage />
        // display this when user starts to scroll, sticky on top of the page
        <StickyHeader ref = {ele => this.stickyHeader = ele} />
     </div> 
   );
 }
}

You can refer this article which worked for me, http://blog.sodhanalibrary.com/2016/07/detect-scroll-direction-using-reactjs.html#.Wo0hq0nTS-4 to add logic inside handleScroll. 您可以参考对我有用的这篇文章http://blog.sodhanalibrary.com/2016/07/detect-scroll-direction-using-reactjs.html#.Wo0hq0nTS-4在handleScroll中添加逻辑。

I generally use this script for sticky header for my header with id="sticky" 我通常将此脚本用于id =“ sticky”标题的粘性标题

$(window).scroll(function () {

    var iCurScrollPos = $(this).scrollTop();
    if (iCurScrollPos) {
     //#sticky put your element for which you want it to apply
        $('#sticky').addClass('stickyMenu');

    } else {
        $('#sticky').removeClass('stickyMenu');
    }

});

Add css for attached class 为附加的类添加CSS

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

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