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

 使用

相关推荐

  1. js如何实现滚动底部一键回顶部

    2024-01-26 20:58:01       52 阅读
  2. React实现抽屉组件

    2024-01-26 20:58:01       64 阅读
  3. React实现虚拟加载滚动

    2024-01-26 20:58:01       52 阅读
  4. [React] 手动实现CountTo 数字滚动效果

    2024-01-26 20:58:01       26 阅读
  5. Vue 和 React 框架实现滚动缓冲区

    2024-01-26 20:58:01       25 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-01-26 20:58:01       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-01-26 20:58:01       100 阅读
  3. 在Django里面运行非项目文件

    2024-01-26 20:58:01       82 阅读
  4. Python语言-面向对象

    2024-01-26 20:58:01       91 阅读

热门阅读

  1. React进阶 - 13(说一说 React 中的虚拟 DOM)

    2024-01-26 20:58:01       65 阅读
  2. Hive之set参数大全-14

    2024-01-26 20:58:01       42 阅读
  3. SpringBoot实现自定义异常+全局异常统一处理

    2024-01-26 20:58:01       55 阅读
  4. 深入理解高阶函数与函数柯里化在React中的应用

    2024-01-26 20:58:01       67 阅读
  5. MySQL之约束

    2024-01-26 20:58:01       54 阅读
  6. CGAL::Plane_3<K>平面结构

    2024-01-26 20:58:01       54 阅读
  7. webpack常见的loader和plugin

    2024-01-26 20:58:01       59 阅读
  8. Android JNI中设置全局的jbyteArray

    2024-01-26 20:58:01       54 阅读
  9. C语言实战系列二:简单超市收银系统

    2024-01-26 20:58:01       53 阅读