无法删除子组件中 React 中的事件侦听器
我有一个父级 React 组件,它具有添加和删除侦听器的方法。它看起来像这样:
const onKeyDown = (e: KeyboardEvent) => {
//Some stuff
e.preventDefault();
};
const addEventListeners = () => {
document.addEventListener("keydown", onKeyDown);
};
const removeEventListeners = () => {
document.removeEventListener("keydown", onKeyDown);
};
我将 addEventListeners 和 removeEventListeners 传递给一些子组件,因为我希望它们添加和删除侦听器。问题是只有 addEventListeners 有效,同时removeEventListeners 似乎不起作用。 addEventListeners 执行的次数与removeEventListeners 执行的次数一样多。
I have a parent react component that has methods to add and remove listeners. It looks like this:
const onKeyDown = (e: KeyboardEvent) => {
//Some stuff
e.preventDefault();
};
const addEventListeners = () => {
document.addEventListener("keydown", onKeyDown);
};
const removeEventListeners = () => {
document.removeEventListener("keydown", onKeyDown);
};
I pass down both addEventListeners and removeEventListeners to some children components because I want them to add and remove listeners. The problem is that only addEventListeners works, meanwhile removeEventListeners doesn't seem to work. addEventListeners is executed as many times as removeEventListeners.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论