react 监听页面滚动

html:

// 如果使用typescript, 定义dom类型 
private dom: HTMLDivElement | null

// ReactJS中,对Div监听只需要绑定 onScrollCapture事件

<div
    style={{
           flex: 1,
           height: '10000px',                    
           overflowY: 'scroll',
           overflowX: 'hidden',                   
         }}
     ref={dom => {this.dom = dom}}
     onScrollCapture={() => this.handleOnScroll()}
    >
    。。。

 </div>

js: 

// 监听页面滚动

private handleOnScroll = () => {
    let flag = false
    if (this.tabdom) {
      const contentScrollTop = this.tabdom.scrollTop
      if (contentScrollTop >= 500) {
        flag = true
      }
      this.setState({
        flag
       }, () => {
        // todo  根据flag 去改变样式或...
        })
    }
  }    

猜你喜欢

转载自www.cnblogs.com/aloehui/p/10402844.html