新建ScrollToTop.js
import React, { useState, useEffect } from 'react';
import './ScrollToTop.css';function ScrollToTop() {const [isVisible, setIsVisible] = useState(true);// Show button when page is scorlled upto given distanceconst toggleVisibility = () => {console.log(1)console.log(window.scrollY)if (window.scrollY > 300) {setIsVisible(true);} else {setIsVisible(false);}};// Set the top cordinate to 0// make scrolling smoothconst scrollToTop = () => {window.scrollTo({top: 0,behavior: "smooth"});};useEffect(() => {window.addEventListener("scroll", toggleVisibility);return () => window.removeEventListener("scroll", toggleVisibility);}, []);return ( isVisible &&<div className="scroll-to-top" onClick={scrollToTop}>{isVisible &&<div onClick={scrollToTop}><i className="icon fas fa-chevron-up">1</i></div>}</div>);
}export default ScrollToTop;
css
.scroll-to-top {position: fixed;bottom: 20px;right: 20px;cursor: pointer;display: flex;justify-content: center;align-items: center;height: 50px;width: 50px;background-color: #007BFF;color: white;border-radius: 50%;transition: visibility 0s, opacity 0.5s linear;
}.scroll-to-top:hover {background-color: #0056b3;
}.icon {font-size: 24px;
}.scroll-to-top.show {visibility: visible;
}
使用