react实现回到顶部
使用 window.scrollTo 方法
通过调用 window.scrollTo 方法,可以平滑滚动到页面顶部。在 React 中,可以在按钮的点击事件中直接调用该方法。
const scrollToTop = () => {
window.scrollTo({
top: 0,
behavior: "smooth"
});
};
// 在组件中调用
<button onClick={scrollToTop}>回到顶部</button>
使用 useEffect 监听滚动状态
如果需要显示或隐藏“回到顶部”按钮,可以结合 useState 和 useEffect 监听页面滚动位置。
import { useState, useEffect } from "react";
const BackToTopButton = () => {
const [isVisible, setIsVisible] = useState(false);
useEffect(() => {
const toggleVisibility = () => {
if (window.pageYOffset > 300) {
setIsVisible(true);
} else {
setIsVisible(false);
}
};
window.addEventListener("scroll", toggleVisibility);
return () => window.removeEventListener("scroll", toggleVisibility);
}, []);
return (
isVisible && (
<button onClick={scrollToTop} className="back-to-top">
回到顶部
</button>
)
);
};
使用第三方库 react-scroll
react-scroll 提供了更丰富的滚动功能,包括平滑滚动和锚点跳转。
import { Link } from "react-scroll";
<Link to="top" smooth={true} duration={500}>
回到顶部
</Link>;
自定义动画效果
如果需要更复杂的动画效果,可以使用 requestAnimationFrame 实现自定义滚动动画。
const scrollToTop = () => {
const c = document.documentElement.scrollTop || document.body.scrollTop;
if (c > 0) {
window.requestAnimationFrame(scrollToTop);
window.scrollTo(0, c - c / 8);
}
};
样式优化
为“回到顶部”按钮添加样式,提升用户体验。
.back-to-top {
position: fixed;
bottom: 20px;
right: 20px;
padding: 10px 15px;
background: #007bff;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
}
.back-to-top:hover {
background: #0056b3;
}






