监听页面滚动条是否在顶部react

import React, { useEffect, useRef, useState } from 'react';

const Component: React.FC = () => {
  const containerRef = useRef<HTMLDivElement>(null); // 使用HTMLDivElement类型作为引用的类型

  const [isAtTop, setIsAtTop] = useState<boolean>(false);

  useEffect(() => {
    const handleScroll = () => {
      const container = containerRef.current;
      if (container && container.scrollTop !== undefined) {
        const { scrollTop } = container;
        const atTop = scrollTop === 0;
        setIsAtTop(atTop);
      }
    };

    const container = containerRef.current;
    container?.addEventListener('scroll', handleScroll);

    return () => {
      const container = containerRef.current;
      container?.removeEventListener('scroll', handleScroll);
    };
  }, []);

  return (
    <div ref={containerRef}>
      {/* Content */}
    </div>
  );
};

export default Component;

你可能感兴趣的:(react.js,javascript,前端)