如果我们想在多个组件中获取当前滚轮的位置,并对其进行操作,这时候就需要将逻辑给抽离出来。
import React from 'react'
import useScrollPosition from '../hooks/scroll-position-hook';
export default function CustomScrollPositionHook() {
const position = useScrollPosition();
return (
<div style={{ padding: "1000px 0" }}>
<h2 style={{ position: "fixed", left: 0, top: 0 }}>CustomScrollPositionHook:{position}</h2>
</div >
)
}
import { useEffect, useState } from "react";
function useScrollPosition() {
const [scrollPosition, setScrollPosition] = useState(0);
// 页面加载完成之后,做个监听。
useEffect(() => {
const handleScroll = () => {
setScrollPosition(window.scrollY)
}
document.addEventListener("scroll", handleScroll);
return () => {
document.removeEventListener("scroll", handleScroll)
}
}, [])
return scrollPosition;
}
export default useScrollPosition;