react实现滚动到顶部组件

新建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 &&
        <div  className="scroll-to-top" onClick={scrollToTop}>
            {isVisible &&
                <div onClick={scrollToTop}>
                    <i className="icon fas fa-chevron-up">1</i>
                </div>}
        </div>
    );
}

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;
}

使用

相关推荐
我叫蒙奇27 分钟前
JS中的隐式类型转换
前端
他们叫我秃子28 分钟前
前端开发转 Go 全栈(四):代码写在前面,却要最后执行?我终于搞懂了 defer
前端·后端·go
生戎马 平安京策1 小时前
只学一点点:我的技术学习策略
前端·javascript·react.js
大鹏说大话1 小时前
HTML5 地理定位 Geolocation:获取用户位置的“红线”与最佳实践
前端·html·html5
Csvn1 小时前
content-visibility: auto —— 让浏览器跳过离屏渲染的性能黑科技
前端
小鹰信息技术服务部1 小时前
Edge安装包MicrosoftEdgeSetup.exe无法运行,点击没反应
前端·edge
webkubor2 小时前
一次前端生产白屏复盘:旧 HTML、Hash 资源和 MIME type text/html
前端·前端工程化
咩咩啃树皮2 小时前
第63篇【终极整合巨作】从零手写原生中后台管理系统|整合62篇全部前端知识点|从头到尾完整架构+全功能逻辑
前端·架构
Highcharts4 小时前
用Highcharts如何动态向一个序列添加点-示列讲解
前端
weixin_431600444 小时前
做 Agent 会用到的 Node API(4):取消与 AbortController
前端·学习·ai·agent·ai编程