react判断滚动到底部以及保持原来的滚动位置

这里解决两个问题:
* 判断某个组件是否滚动到底部
* 页面切换出去再切换回来后怎样保持之前的滚动位置

要保证这个组件就是那个滚动的组件,overflowY为scroll

判断某个组件是否滚动到底部

  • 组件代码如下,通过ref获取真实的dom节点
<div ref={ node => this.contentNode = node }>
  • 在组件加载完成后增加监听scroll事件,组件将要卸载的时候移除事件,onScrollHandle里面就可以判断是否滚动到了底部
  onScrollHandle(event) {
    const clientHeight = event.target.clientHeight
    const scrollHeight = event.target.scrollHeight
    const scrollTop = event.target.scrollTop
    const isBottom = (clientHeight + scrollTop === scrollHeight)
    console.log('is bottom:' + isBottom)
  }

  componentDidMount() {
    if (this.contentNode) {
      this.contentNode.addEventListener('scroll', this.onScrollHandle.bind(this));
    }
  }

  componentWillUnmount() {
    if (this.contentNode) {
      this.contentNode.removeEventListener('scroll', this.onScrollHandle.bind(this));
    }
  }

页面切换出去再切换回来后怎样保持之前的滚动位置

  • 当页面切换出去的时候会调用componentWillUnmount方法,所以在这里记录下当前组件位置
  • 当页面切换进来的时候会调用componentDidMount方法,将之前保存的位置重新赋值给组件
    代码如下:
let scrollTop = 0
onScrollHandle(event) {
    const clientHeight = event.target.clientHeight
    const scrollHeight = event.target.scrollHeight
    const scrollTop = event.target.scrollTop
    const isBottom = (clientHeight + scrollTop === scrollHeight)
    if (this.state.isScrollBottom !== isBottom) {
      this.setState({
        isScrollBottom: isBottom
      })
    }
  }

  componentDidMount() {
    if (this.contentNode) {
      this.contentNode.addEventListener('scroll', this.onScrollHandle.bind(this));
      this.contentNode.scrollTop = scrollTop
    }
  }

  componentWillUnmount() {
    if (this.contentNode) {
      this.contentNode.removeEventListener('scroll', this.onScrollHandle.bind(this));
      scrollTop = this.contentNode.scrollTop
    }
  }

scrollTop放在类外面作为全局变量

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值