Home>Article>Web Front-end> Problems in implementing tab ceiling using react.js
There is a requirement in react project development that when the page scrolls to the location of the tab, the tab should be fixed at the top.
The implementation idea is actually very simple, which is to determine when the scroll distance scrollTop is greater than the distance between the tab and the top of the page offsetTop, and change the position of the tab to fixed.
In react, I set a navTop attribute in the state, switch the value of this attribute to true or false, and then use the classnames() method on the tab tag to add the class name fixed using the value of navTop.
At first I wrote like this:
import cs from 'classnames'; class FixedTab extends React.Component{ constructor(props){ super(props); this.state = { navTop: false } this.$tab = null; this.offsetTop = 0; } componentDidMount(){ this.$tab = this.refs.tab; if(this.$tab){ this.offsetTop = this.$tab.offsetTop; window.addEventListener('scroll',this.handleScroll); } } handleScroll(){ let sTop = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop; if(sTop >= this.offsetTop){ this.setState({ navTop: true }) } if(sTop < this.offsetTop){ this.setState({ navTop:false }) } } render(){ return( ) } }
Then I found a problem with writing like this. When the scrolling distance of my scroll bar reaches the condition, the tab is The ceiling-ceiling effect appeared, but it was restored in an instant, and the scroll bar also rebounded, making it impossible to continue pulling down.
At first I thought there was a problem with the judgment logic, but I could never find a solution. Later I suspected that it was caused by the time difference between state value changes. It seemed that I was stuck in an infinite loop, and then I was judging the scrolling distance. Previously, a function was added to determine the status of navTop.
The main modified code is as follows:
handleScroll(){ let sTop = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop; if(!this.state.navTop && sTop >= this.offsetTop){ this.setState({ navTop: true }) } if(sTop < this.offsetTop){ this.setState({ navTop:false }) } }
After this modification, the ceiling effect will be normal.
The above is the detailed content of Problems in implementing tab ceiling using react.js. For more information, please follow other related articles on the PHP Chinese website!