React 组件平滑滚动到顶部

2025-05-26

React 组件平滑滚动到顶部

在现代博客网站上,尤其是那些需要 15 分钟阅读时间的博客网站上,很少能找到一个可以平滑滚动到页面顶部的按钮!

然而,每当我遇到它时,我总是倾向于使用它,并欣赏这个具有如此特殊功能的简单按钮的优雅。

在仔细阅读Stack OverflowGitHub 上的解决方案后,我偶然发现了一个使用 Hooks 的优雅 React 组件,并想与社区分享它!

我们的按钮应该像这样工作:
替代文本

以下是我们组件的测试用例:

  • 按钮应始终位于页面右下角
  • 按钮应该隐藏,并且只有当我们滚动到一定高度时才显示
  • 点击它后,我们应该顺利地转到页面顶部

Hook组件实现了以下功能。



import React, { useEffect, useState } from "react";

export default function ScrollToTop() {
  const [isVisible, setIsVisible] = useState(false);

  // Top: 0 takes us all the way back to the top of the page
  // Behavior: smooth keeps it smooth!
  const scrollToTop = () => {
    window.scrollTo({
      top: 0,
      behavior: "smooth"
    });
  };

  useEffect(() => {
    // Button is displayed after scrolling for 500 pixels
    const toggleVisibility = () => {
      if (window.pageYOffset > 500) {
        setIsVisible(true);
      } else {
        setIsVisible(false);
      }
    };

    window.addEventListener("scroll", toggleVisibility);

    return () => window.removeEventListener("scroll", toggleVisibility);
  }, []);

//scroll-to-top classes: fixed, bottom:0, right:0
  return (
    <div className="scroll-to-top">
      {isVisible && (
        <div onClick={scrollToTop}>
          <h3>Go up!</h3>
        </div>
      )}
    </div>
  );
}


Enter fullscreen mode Exit fullscreen mode

快完成了!只需将此组件导入到你的 React 文件中,并将其粘贴到最后即可。

瞧,它应该可以工作了!

是一个关于它应该如何运作的基本、快速且丑陋的演示!

文章来源:https://dev.to/prnvbirajdar/react-hooks-component-to-smooth-scroll-to-the-top-35fd
PREV
100 个 AWS DevOps 面试问题及答案
NEXT
使用 Next.js 和 DEV.to 构建博客的资源