使用 chakra ui 创建“返回顶部”按钮

问题描述

我正在尝试使用 Chakra Ui 创建返回顶部按钮,但不确定如何仅在用户滚动一点(例如在标题部分之后或 500 像素之后)后才显示 BTT 按钮

<Link to='/#top'>
        <Box position='fixed'
            bottom='20px'
            right={['16px','84px','120px']}
            zIndex={2}
        >
            <Image src='images/icons/top.svg'
                w='60px'
                h='60px'
            />
        </Box>
    </Link>

解决方法

好的,我找到了解决方案,如果有人在这里遇到同样的问题,我是怎么做的:

const [scrollPosition,setScrollPosition] = useState(0);
const handleScroll = () => {
    const position = window.pageYOffset;
    setScrollPosition(position);
};

useEffect(() => {
    window.addEventListener('scroll',handleScroll,{ passive: true });

    return () => {
        window.removeEventListener('scroll',handleScroll);
    };
},[]);

然后在组件中:

{scrollPosition > 500 && (<Link href='/#top'>
            <Box position='fixed'
                bottom='20px'
                right={['16px','84px']}
                zIndex={1}
            >
                <Image src='images/icons/top.svg'
                    w='60px'
                    h='60px'
                />
            </Box>
        </Link>)}