簡體   English   中英

如何在react.js中滾動顯示/隱藏組件

[英]How to make a component show/hide on scroll in react.js

我只是在用戶向下滾過標題時嘗試制作頁腳橫幅,並在用戶向上滾動到頂部時隱藏它。 我對如何實現這個的想法是在頁面的頂部組件中為scroll事件添加一個事件監聽器。 這是我目前的代碼。 但它不起作用:

componentDidMount() {
  this.nv.addEventListener('scroll', this.handleScroll);
}

handleScroll(e) {
  if(window.pageYOffset > 50 && window.pageYOffset < 900) {
    console.log('scrolled');
    this.setState({
      showBanner: true,
    });
  } else {
    this.setState({
      showBanner: false,
    });
  }
}

頂級組件的渲染方法:

render() {
  return (
    <div ref={elem => this.nv = elem}>
      <Header/>
      <Body
        userInfo={this.props.userInfo}
        history={this.props.history}
      />
      {
        this.state.showBanner && <Banner/>
        || null
      }
    </div>
  )
}

我沒有看到任何日志,滾動時顯然沒有調用setState

關於如何實現預期目標的任何建議?

* UPDATE *更改了componentDidMount以在窗口上添加事件監聽器,現在它正在工作。

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

原因是您正在嘗試將事件偵聽器添加到尚不存在的引用中。 componentDidMount在初始渲染之前發生。 這意味着您在渲染中分配的引用尚未設置。

您可以使用ref回調並在其中附加事件偵聽器:

applyRef = ref => {
  this.vn = ref;
  this.vn.addEventListener('scroll', this.handleScroll);
}
render() {
  return (
    <div ref={this.applyRef}>
      <Header/>
      <Body
        userInfo={this.props.userInfo}
        history={this.props.history}
      />
      {
        this.state.showBanner && <Banner/>
        || null
      }
    </div>
  )
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM