React 監聽頁面滾動,界面動態顯示


當頁面滾動時,如何動態切換布局/樣式

 

1. 添加滾動事件的監聽/注銷

//在componentDidMount,進行scroll事件的注冊,綁定一個函數,讓這個函數進行監聽處理
componentDidMount() {
window.addEventListener('scroll', this.bindHandleScroll)
}
//在componentWillUnmount,進行scroll事件的注銷
componentWillUnmount() {
window.removeEventListener('scroll', this.bindHandleScroll);
}
bindHandleScroll = (event) => {

}

 

2. 在state中添加參數,滾動頁面時更新數據

更新參數后,設置樣式。可以直接更新樣式,也可以動態修改className然后在css文件中添加動態樣式。

bindHandleScroll = (event) => {
// 滾動的高度
const scrollTop = (event.srcElement ? event.srcElement.documentElement.scrollTop : false)
|| window.pageYOffset
|| (event.srcElement ? event.srcElement.body.scrollTop : 0);
this.setState({
hasVerticalScrolled: scrollTop > 10
})
}
render() {
return (
<div className="header-container" style={{backgroundColor:this.state.hasVerticalScrolled?'#ffffff':'transparent'}}>
<div className="headerTitle-container">
<img className={`headerTitle${this.state.hasVerticalScrolled ? '-scrolled' : ''}`}></img>
</div>
</div>
);
}

vi設計http://www.maiqicn.com 辦公資源網站大全https://www.wode007.com

完整Code: 

import react, { Component } from 'react';
import './style.less';

interface PropsData {
}
interface StateData {
hasVerticalScrolled: boolean;
}

class Index extends Component<PropsData, StateData> {
constructor(props) {
super(props);
this.state = {
hasVerticalScrolled: false
};
}

//在componentDidMount,進行scroll事件的注冊,綁定一個函數,讓這個函數進行監聽處理
componentDidMount() {
window.addEventListener('scroll', this.bindHandleScroll)
}
//在componentWillUnmount,進行scroll事件的注銷
componentWillUnmount() {
window.removeEventListener('scroll', this.bindHandleScroll);
}
bindHandleScroll = (event) => {
// 滾動的高度
const scrollTop = (event.srcElement ? event.srcElement.documentElement.scrollTop : false)
|| window.pageYOffset
|| (event.srcElement ? event.srcElement.body.scrollTop : 0);
this.setState({
hasVerticalScrolled: scrollTop > 10
})
}
render() {
return (
<div className="header-container" style={{backgroundColor:this.state.hasVerticalScrolled?'#ffffff':'transparent'}}>
<div className="headerTitle-container">
<img className={`headerTitle${this.state.hasVerticalScrolled ? '-scrolled' : ''}`}></img>
</div>
</div>
);
}
}

export default Index;


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM