react判斷滾動到底部以及保持原來的滾動位置
阿新 • • 發佈:2018-12-27
這裡解決兩個問題:
* 判斷某個元件是否滾動到底部
* 頁面切換出去再切換回來後怎樣保持之前的滾動位置
要保證這個元件就是那個滾動的元件,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放在類外面作為全域性變數