首页 > 解决方案 > 如何将 document.addEventListener("scroll") 放在其他文件中以在我的组件中调用它?

问题描述

我有这段代码,我可以用它检查何时到达bottoma :divscrolling

const checkBottomDiv = (el: HTMLElement) => {
  return el.getBoundingClientRect().bottom - 400 <= window.innerHeight;
};

const contentArticleId = document.getElementById("myDiv") as HTMLElement;

const trackScrolling = () => {
  callback();

  if (checkBottomDiv(contentArticleId)) {
    console.log("bottomDiv");
    document.removeEventListener("scroll", trackScrolling);
  }
};
document.addEventListener("scroll", trackScrolling);

我想在其他地方重用这个功能,components因此,我想把这个逻辑放在一个单独的函数中,然后调用它(function.ts)。

我正在这样做:

app.tsx.  //component

useEffect(() => {
  let element = document.getElementById("myDiv") as HTMLElement;
  trackScrolling(element, callback);
})


function.ts. //function file

const checkBottomDiv = (el: HTMLElement) => {
  return el.getBoundingClientRect().bottom - 400 <= window.innerHeight;
};

export const trackScrolling = (element: HTMLElement, callback: () => void) => {
  if (checkBottomDiv(element)) {
    callback();
    document.removeEventListener("scroll", trackScrolling);
  }
};
document.addEventListener("scroll", trackScrolling);

但我得到了我不知道如何解决的错误。

这是我的实时代码:

https://codesandbox.io/s/epic-solomon-hu3e3

我做错了什么,我该如何解决。

标签: javascriptreactjsdom

解决方案


即使可以,但实际上您可能不想这样做。更好的方法是在 componentDidMount 生命周期或 useEffect 挂钩中附加事件侦听器。这转换为以下代码:

const MyWrapperComponent = (props) => {
  useEffect(()=>{
    document.addEventListener('scroll', (e)=>{
       // do something
    });
    return ()=>{
      document.removeEventListener("scroll");
    }
  },[]);
}

但是由于您想在许多组件中使用滚动事件,将这个 useEffect 钩子放在所有组件中会使您的代码变得意大利面,所以为了避免这种情况,您可以使用上下文 API 与所有需要它的组件共享事件数据.


推荐阅读