用React写一个小巧的返回顶部组件(BackToTop)

二狗2022/03/06发布
react
next

components/BackToTop.jsx
'use client'; // 客户端组件,不是Next项目的话删掉吧

import { useState, useEffect } from 'react';

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

  // 滚动距离
  const handleScroll = () => setIsVisible(window.scrollY > 300);
  // 点击此函数将滚动到页面顶部
  const scrollToTop = () => window.scrollTo({ top: 0, behavior: 'smooth' });

  useEffect(() => {
    window.addEventListener('scroll', handleScroll);
    return () => window.removeEventListener('scroll', handleScroll);
  }, []);

  return (
    <>
      {isVisible && (
        <button
          onClick={scrollToTop}
          className="fixed bottom-3 right-3 cursor-pointer bg-white border-primary shadow-lg w-12 h-12 rounded-xl flex items-center justify-center"
        >
          <svg
            xmlns="http://www.w3.org/2000/svg"
            width="24"
            height="24"
            fill="currentColor"
            className="fill-gray-500 w-6 h-6"
          >
            <path d="M11 20V7.825l-5.6 5.6L4 12l8-8 8 8-1.4 1.425-5.6-5.6V20Z"></path>
          </svg>
        </button>
      )}
    </>
  );
}

#引用

jsx
import BackToTop from './components/BackToTop';

function App() {
  return (
    <div className="App">
       <BackToTop />
    </div>
  );
}

export default App;