import React, { useState, useEffect, useRef } from "react"; import { ArrowUp } from "lucide-react"; import { Button } from "@/components/ui/button"; const ScrollToTop = () => { const [isVisible, setIsVisible] = useState(false); const sentinelRef = useRef(null); useEffect(() => { // 创建观察器实例 const observer = new IntersectionObserver( ([entry]) => { // 当哨兵元素可见时隐藏按钮,不可见时显示按钮 setIsVisible(!entry.isIntersecting); }, { // 将观察点设置在页面30%的位置(即滚动70%时触发) rootMargin: "60% 0px -40% 0px", threshold: 0, } ); // 开始观察哨兵元素 if (sentinelRef.current) { observer.observe(sentinelRef.current); } // 清理观察器 return () => { if (sentinelRef.current) { observer.unobserve(sentinelRef.current); } }; }, []); const scrollToTop = () => { window.scrollTo({ top: 0, behavior: "smooth", }); }; return ( <> {/* 哨兵元素放在页面顶部 */}
{/* 回到顶部按钮 */}