react监控页面滚动的简单应用其实很简单,在组件的生命周期函数 componentDidMount 中让window调用它的 onscroll 方法就可以啦
componentDidMount(){
let ctx = this;
window.onscroll = function () {
if( window.pageYOffset > 170)
{
ctx.setState({
open:true,
})
}
}
}
注意不能直接用this.setState来设置open,这里open控制Snackbar的显隐
<Snackbar
id="Snackbar"
open={this.state.open}
message="滚动距离大于170了"
autoHideDuration={4000}
/>