Determine the distance of the scrollbar in the Mount update (the scrollbar cannot overflow:auto the pit)
componentDidMount(){
window.addEventListener(‘scroll‘ , ()=>{
let scrollTop = document.documentElement.scrollTop || document.body/scrollTop;
if(scrollTop > 500){
this.setState({
show : true
})
}else{
this.setState({
show : false
})
}
})
}
Define a displayed variable in this.state= ({})
constructor(props){
super(props)
this.state = ({
show : false
})
}
Inside the JSX syntax
render() {
let { show } = this.state;
return (
<div className="common-back">
{
show &&
<div onClick={this.goTo} className="iconfont icon-huidaodingbu1"></div>
}
</div>
);
}
Then click Back to the top, animated, no animations with Window.scrollto (0,0);
goTo(){
let scrollToTop = window.setInterval(function() {
let pos = window.pageYOffset;
if ( pos > 0 ) {
window.scrollTo( 0, pos - 20 ); // how far to scroll on each step
} else {
window.clearInterval( scrollToTop );
}
}, 2);
}
React component back to top