Ars*_*niy 7 events scroll typescript reactjs
我在滚动上添加了侦听器,并尝试使用事件。我如何描述 type 而不是 any ?
反应 16.8.6 Tpescript 3.4
const Component: FC<IProps> = ({ children, scrollOffset, getScrollTop, videoListScrollUpdate }) => {
const scroller = useRef<HTMLDivElement>(null)
useEffect(() => {
if (scrollOffset && scroller.current) {
scroller.current.scrollTop = scrollOffset
return
}
if (getScrollTop && scroller.current) {
scroller.current.addEventListener('scroll', (e: any) => getScrollTop(e.target.scrollTop))
}
}, [])
}
Run Code Online (Sandbox Code Playgroud)
iam*_*lli 11
您可以使用
(e: React.UIEvent<HTMLElement>). 在来自 SyntheticEvents的UIEvent下描述。
也就是说,我建议不要useRef在useEffect. 确定是否被重新调用并且不为空是很棘手的(甚至可能会误导它)。useEffectscroller.currentconsole.log
但是,我建议改为onScroll在要附加ref到的组件上使用内置道具,并给它一个回调来处理滚动。这样你就不需要在 useEffect 钩子中手动附加它,你忘记在卸载时删除它(内存泄漏问题)。
interface IProps {
children: React.ReactNode;
getScrollTop: (scrollTop: number) => whatever;
// Your other Props
}
const ScrollComponent: React.FC<IProps> = ({
children,
getScrollTop,
// Your other props
}): JSX.Element => {
const handleScroll = (e: React.UIEvent<HTMLElement>): void => {
e.stopPropagation() // Handy if you want to prevent event bubbling to scrollable parent
console.log({
event: e,
target: e.target, // Note 1* scrollTop is undefined on e.target
currentTarget: e.currentTarget,
scrollTop: e.currentTarget.scrollTop,
});
const { scrollTop } = e.currentTarget;
getScrollTop(scrollTop);
};
return (
<div
// I am assuming you were referencing your scroller as follows.
// ref={scroller}
onScroll={handleScroll} // Use the onScroll prop instead.
>
{children}
</div>
);
};
Run Code Online (Sandbox Code Playgroud)
Note *1: scrollTop不会在 上可用e.target.scrollTop,就像您在 中看到的那样console.log,但是在 上e.currentTarget.scrollTop,因为currentTarget调用事件处理程序附加到的元素。
| 归档时间: |
|
| 查看次数: |
15626 次 |
| 最近记录: |