react 监听页面滚动

时间:2023-03-09 20:16:32
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.dom) {
const contentScrollTop = this.dom.scrollTop
if (contentScrollTop >= 500) {
flag = true
}
this.setState({
flag
}, () => {
// todo 根据flag 去改变样式或...
})
}
}