如何描述类型滚动事件?

2024-04-20

我在滚动上添加了侦听器,并尝试使用事件。我如何描述 type 而不是 any ?

反应16.8.6 脚本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))
        }
    }, [])

}

您可以使用(e: React.UIEvent<HTMLElement>)。下描述的UIEvent https://reactjs.org/docs/events.html#ui-events来自综合事件。

也就是说,我建议不要使用useRef在一个useEffect. 这很棘手 https://medium.com/@teh_builder/ref-objects-inside-useeffect-hooks-eb7c15198780以确定是否useEffect被重新召回并且scroller.current不为空(甚至console.log可能会产生误导)。

不过我建议改用内置的onScroll您要附加的组件上的 propref到,并给它一个回调来处理滚动。这样,您就不需要在 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>
  );
};

Note *1: 滚动顶部将无法在e.target.scrollTop,正如您在console.log,但是在e.currentTarget.scrollTop, since 当前目标 https://github.com/DefinitelyTyped/DefinitelyTyped/issues/11508#issuecomment-256045682调用事件处理程序所附加到的元素。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何描述类型滚动事件? 的相关文章

随机推荐