Skip to content

Commit 1326eaa

Browse files
committed
add raf
1 parent 7e5724c commit 1326eaa

File tree

1 file changed

+35
-24
lines changed

1 file changed

+35
-24
lines changed

src/stickyScrollBar.tsx

Lines changed: 35 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import getScrollBarSize from 'rc-util/lib/getScrollBarSize';
66
import * as React from 'react';
77
import TableContext from './context/TableContext';
88
import { useLayoutState } from './hooks/useFrame';
9+
import raf from 'rc-util/lib/raf';
910

1011
interface StickyScrollBarProps {
1112
scrollBodyRef: React.RefObject<HTMLDivElement>;
@@ -39,6 +40,14 @@ const StickyScrollBar: React.ForwardRefRenderFunction<unknown, StickyScrollBarPr
3940
x: 0,
4041
});
4142
const [isActive, setActive] = React.useState(false);
43+
const rafRef = React.useRef<number | null>(null);
44+
45+
React.useEffect(
46+
() => () => {
47+
raf.cancel(rafRef.current);
48+
},
49+
[],
50+
);
4251

4352
const onMouseUp: React.MouseEventHandler<HTMLDivElement> = () => {
4453
setActive(false);
@@ -81,30 +90,32 @@ const StickyScrollBar: React.ForwardRefRenderFunction<unknown, StickyScrollBarPr
8190
};
8291

8392
const checkScrollBarVisible = () => {
84-
if (!scrollBodyRef.current) {
85-
return;
86-
}
87-
const tableOffsetTop = getOffset(scrollBodyRef.current).top;
88-
const tableBottomOffset = tableOffsetTop + scrollBodyRef.current.offsetHeight;
89-
const currentClientOffset =
90-
container === window
91-
? document.documentElement.scrollTop + window.innerHeight
92-
: getOffset(container).top + (container as HTMLElement).clientHeight;
93-
94-
if (
95-
tableBottomOffset - getScrollBarSize() <= currentClientOffset ||
96-
tableOffsetTop >= currentClientOffset - offsetScroll
97-
) {
98-
setScrollState(state => ({
99-
...state,
100-
isHiddenScrollBar: true,
101-
}));
102-
} else {
103-
setScrollState(state => ({
104-
...state,
105-
isHiddenScrollBar: false,
106-
}));
107-
}
93+
rafRef.current = raf(() => {
94+
if (!scrollBodyRef.current) {
95+
return;
96+
}
97+
const tableOffsetTop = getOffset(scrollBodyRef.current).top;
98+
const tableBottomOffset = tableOffsetTop + scrollBodyRef.current.offsetHeight;
99+
const currentClientOffset =
100+
container === window
101+
? document.documentElement.scrollTop + window.innerHeight
102+
: getOffset(container).top + (container as HTMLElement).clientHeight;
103+
104+
if (
105+
tableBottomOffset - getScrollBarSize() <= currentClientOffset ||
106+
tableOffsetTop >= currentClientOffset - offsetScroll
107+
) {
108+
setScrollState(state => ({
109+
...state,
110+
isHiddenScrollBar: true,
111+
}));
112+
} else {
113+
setScrollState(state => ({
114+
...state,
115+
isHiddenScrollBar: false,
116+
}));
117+
}
118+
});
108119
};
109120

110121
const setScrollLeft = (left: number) => {

0 commit comments

Comments
 (0)