React 监听页面滚动,界面动态显示

当页面滚动时,如何动态切换布局/样式

1. 添加滚动事件的监听/注销

 1     //在componentDidMount,进行scroll事件的注册,绑定一个函数,让这个函数进行监听处理
 2     componentDidMount() {
 3         window.addEventListener('scroll', this.bindHandleScroll)
 4     }
 5     //在componentWillUnmount,进行scroll事件的注销
 6     componentWillUnmount() {
 7         window.removeEventListener('scroll', this.bindHandleScroll);
 8     }
 9     bindHandleScroll = (event) => {
10 
11     }

2. 在state中添加参数,滚动页面时更新数据

更新参数后,设置样式。可以直接更新样式,也可以动态修改className然后在css文件中添加动态样式。

 1     bindHandleScroll = (event) => {
 2         // 滚动的高度
 3         const scrollTop = (event.srcElement ? event.srcElement.documentElement.scrollTop : false)
 4             || window.pageYOffset
 5             || (event.srcElement ? event.srcElement.body.scrollTop : 0);
 6         this.setState({
 7             hasVerticalScrolled: scrollTop > 10
 8         })
 9     }
10     render() {
11         return (
12             <div className="header-container" style={{backgroundColor:this.state.hasVerticalScrolled?'#ffffff':'transparent'}}>
13                 <div className="headerTitle-container">
14                     <img className={`headerTitle${this.state.hasVerticalScrolled ? '-scrolled' : ''}`}>img>
15                 div>
16             div>
17         );
18     }

完整Code:

 1 import React, { Component } from 'react';
 2 import './style.less';
 3 
 4 interface PropsData {
 5 }
 6 interface StateData {
 7     hasVerticalScrolled: boolean;
 8 }
 9 
10 class Index extends Component<PropsData, StateData> {
11     constructor(props) {
12         super(props);
13         this.state = {
14             hasVerticalScrolled: false
15         };
16     }
17 
18     //在componentDidMount,进行scroll事件的注册,绑定一个函数,让这个函数进行监听处理
19     componentDidMount() {
20         window.addEventListener('scroll', this.bindHandleScroll)
21     }
22     //在componentWillUnmount,进行scroll事件的注销
23     componentWillUnmount() {
24         window.removeEventListener('scroll', this.bindHandleScroll);
25     }
26     bindHandleScroll = (event) => {
27         // 滚动的高度
28         const scrollTop = (event.srcElement ? event.srcElement.documentElement.scrollTop : false)
29             || window.pageYOffset
30             || (event.srcElement ? event.srcElement.body.scrollTop : 0);
31         this.setState({
32             hasVerticalScrolled: scrollTop > 10
33         })
34     }
35     render() {
36         return (
37             <div className="header-container" style={{backgroundColor:this.state.hasVerticalScrolled?'#ffffff':'transparent'}}>
38                 <div className="headerTitle-container">
39                     <img  className={`headerTitle${this.state.hasVerticalScrolled ? '-scrolled' : ''}`}>img>
40                 div>
41             div>
42         );
43     }
44 }
45 
46 export default Index;
View Code

 

你可能感兴趣的:(React 监听页面滚动,界面动态显示)