javascript - 如何将 document.addEventListener("scroll") 放在其他文件中以在我的组件中调用它?
问题描述
我有这段代码,我可以用它检查何时到达bottom
a :div
scrolling
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
我做错了什么,我该如何解决。
解决方案
即使可以,但实际上您可能不想这样做。更好的方法是在 componentDidMount 生命周期或 useEffect 挂钩中附加事件侦听器。这转换为以下代码:
const MyWrapperComponent = (props) => {
useEffect(()=>{
document.addEventListener('scroll', (e)=>{
// do something
});
return ()=>{
document.removeEventListener("scroll");
}
},[]);
}
但是由于您想在许多组件中使用滚动事件,将这个 useEffect 钩子放在所有组件中会使您的代码变得意大利面,所以为了避免这种情况,您可以使用上下文 API 与所有需要它的组件共享事件数据.
推荐阅读
- linux - 检查是否在 cron 中设置了文件路径
- twilio - 如何在 ekata_reverse_phone 上的 twilio Addons 中打印/获取特定数据
- java - 如何将此 curl 命令转换为 java 命令
- ios - 带密码的 LiveView 表单 - iOS Safari 密码保存弹出窗口
- soap - 使用 node-soap 发送带有 XML 和 WS-security 的 SOAP 请求?
- python - 属性“运行”已经在主文件中
- html - 样式化相对于兄弟元素的相对位置
- python - Django 2 函数调用 - 2 个不同的结果
- spring-data-jpa - 如何编写规范以急切地获取惰性多对多关系?
- node.js - 社交和本地认证 + 节点 js + react native + 身份服务器