import React, { useState, useEffect } from "react";
import { VerticalAlignTopOutlined } from '@ant-design/icons';

const ScrollToTop = () => {
    const [show, setShow] = useState(false);
    // 返回顶部
    const backTop = () => {
        const s = document.body.scrollTop;
        if (s > 0) {
            // 要求浏览器在下次重绘之前调用 backTop 回调函数更新动画
            window.requestAnimationFrame(backTop)
            document.body.scrollTop = document.documentElement.scrollTop = s - s / 8;
        }
    }
    // 是否显示返回顶部
    useEffect(() => {
        const handleScroll = (e) => {
            if (e.target.scrollTop > 400) {
                setShow(true)
            } else {
                setShow(false)
            }
        }
        document.addEventListener('scroll', handleScroll, true)
        return () => document.removeEventListener('scroll', handleScroll)
    }, [show])
    return (<>
        {show && (
            <div
                style={{
                    position: 'fixed',
                    width: 40,
                    height: 40,
                    right: 100,
                    bottom: 50,
                    zIndex: 9999,
                    backgroundColor: '#58BE70',
                    borderRadius: '50%',
                    display: 'flex',
                    justifyContent: 'center',
                    alignItems: 'center',
                    cursor: 'pointer',
                }}
                onClick={backTop}
            >
                <VerticalAlignTopOutlined
                    style={{
                        fontSize: '24px',
                        color: '#fff',
                    }}
                />
            </div>
        )}
    </>)
}
export default ScrollToTop;