當頁面滾動時,如何動態切換佈局/樣式 1. 添加滾動事件的監聽/註銷 1 //在componentDidMount,進行scroll事件的註冊,綁定一個函數,讓這個函數進行監聽處理 2 componentDidMount() { 3 window.addEventListener('scroll', ...
當頁面滾動時,如何動態切換佈局/樣式
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