react实现滚动到顶部组件

react实现滚动到顶部组件_第1张图片

新建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 distance
    const 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 smooth
    const scrollToTop = () => {
        window.scrollTo({
            top: 0,
            behavior: "smooth"
        });
    };

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

    return ( isVisible &&
        
{isVisible &&
1
}
); } 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;
}

 使用

你可能感兴趣的:(react.js,html,前端)