53.React学习笔记.自定义hook练习-scroll

如果我们想在多个组件中获取当前滚轮的位置,并对其进行操作,这时候就需要将逻辑给抽离出来。

import React from 'react'
import useScrollPosition from '../hooks/scroll-position-hook';
export default function CustomScrollPositionHook() {
  const position = useScrollPosition();
  return (
    

CustomScrollPositionHook:{position}

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

你可能感兴趣的:(53.React学习笔记.自定义hook练习-scroll)