import React, { HTMLAttributes, useEffect, useRef, useState } from 'react'; import classNames from 'classnames'; import './index.scss'; export interface AffixProps extends HTMLAttributes { container?: HTMLElement | null; children?: React.ReactNode; offsetTop?: number; offsetBottom?: number; rowPosition?: 'start' | 'center' | 'end'; } const Affix: React.FC = (props) => { const { children, container, offsetBottom, rowPosition, offsetTop, ...rest } = props; const containerRef = useRef(null); const contentRef = useRef(null); const leftPosition = useRef(0); const [shouldFixed, setFixed] = useState(false); const scrollHandle = () => { const { top } = containerRef.current!.getBoundingClientRect(); if (top < offsetTop!) setFixed(true); if (top > offsetTop!) setFixed(false); }; useEffect(() => { const { left } = contentRef.current!.getBoundingClientRect(); leftPosition.current = left; if (container) container.addEventListener('scroll', scrollHandle); return () => { document.removeEventListener('scroll', scrollHandle); }; }, []); return (
{children}
); }; Affix.defaultProps = { children: '', offsetBottom: 0, offsetTop: 0, rowPosition: 'start', container: document.body }; export default Affix;