react判断滚动到底部以及保持原来的滚动位置
来源:互联网 发布:u盘数据恢复 免费 编辑:程序博客网 时间:2024/06/14 22:04
这里解决两个问题:
* 判断某个组件是否滚动到底部
* 页面切换出去再切换回来后怎样保持之前的滚动位置
要保证这个组件就是那个滚动的组件,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 = 0onScrollHandle(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放在类外面作为全局变量
阅读全文
1 0
- react判断滚动到底部以及保持原来的滚动位置
- 判断滚动滚动到底部
- 页面刷新后跳滚动条保持原来的位置
- 页面滚动条 刷新后 保持在原来的位置
- 判断滚动条到底部的方法
- js 判断滚动条滚动到底部
- ListView滚动到底部判断
- ListView滚动到底部判断
- 滚动到底部判断条件
- Android 记录ListView滚动的位置的三种方法及判断是否滑动到底部
- 判断scroll是否滚动到底部以及实现回到顶部
- 滚动条循环,判断滚动条滚动到底部
- 保持页面中滚动条的位置,使得页面提交后滚动条还是在原来的位置
- JS及jQuery获取各种宽度、高度的简单介绍以及判断滚动条滚动到底部事件
- jquery 滚动条 平滑滚动到顶部、底部、置顶位置
- JS 判断滚动条到底部的JS代码
- 判断滚动条到底部的JS代码
- ListView滚动到顶部和底部的判断
- 使用flex固定头部和底部中间滚动
- python中装饰器的理解
- HDU 6161 树形DP + 优化
- 输入地名获取相应的百度坐标
- MySQL——修改root密码的4种方法(以windows为例)
- react判断滚动到底部以及保持原来的滚动位置
- HTML canvas画布
- js库支持CommonJs和浏览器的标准写法
- Net面试题
- Redis和消息队列使用实战
- Spring配置三大数据库连接池
- [FAQ14169][Audio APP]Music、FM等apk在播放或运行时,从recent app list中删除后,如何实现music、FM等apk立即停止?
- fetch跨域post,后端express
- 使用cookie自动登录出现Cannot forward after response has been committed和必须刷新第二次才能进入到页面