欢迎访问Ningto's博客

Menu
  • 首页
  • 归档
  • 关于
  • 书签
  • 必应壁纸
  • IT聚合
  • 工具
    • 我的工具列表
    • 我的网盘
    • 必应每日壁纸API
    • Html转Markdown
    • 仙尘光标
Menu

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

最后更新 2017-07-25 10:10:14   阅读量 3665

Table of Contents

  • 1. 判断某个组件是否滚动到底部
  • 2. 页面切换出去再切换回来后怎样保持之前的滚动位置

这里解决两个问题:

  • 判断某个组件是否滚动到底部
  • 页面切换出去再切换回来后怎样保持之前的滚动位置

要保证这个组件就是那个滚动的组件,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放在类外面作为全局变量

(转载本站文章请注明作者和出处:泞途 - ningto.com)

下一篇 – 使用flex固定头部和底部中间滚动
上一篇 – js库支持CommonJs和浏览器的标准写法

  1. Web

toningto@outlook.com

标签云

Go Java Javascript Shell C/C++ MQ MongoDB Node.js Linux Tools Mac Boost Python Product Web Others Design Database Bug Windows Qt React IOS Life Mobile Android Tips

推广链接

【腾讯云】云产品限时秒杀,爆款1核2G云服务器,首年99元

多谢支持,用了好几年,服务很稳定支持多设备!

其他

文章RSS

Copyright © 2016 Welcome To Ningto Blog | 鄂ICP备17003086号-2