[英]How to pass arguments to addEventListener listener function with typescript?
The situation is somewhat like:情况有点像:
const searchKeyPressHandler = (appDispatch: any, e: any) => {
if (e.keyCode === 27) {
appDispatch({ type: "closeSearch" })
}
}
document.addEventListener("keyup", searchKeyPressHandler); // <-- error on searchKeyPressHandler
return () => document.removeEventListener("keyup", searchKeyPressHandler); // <-- error on searchKeyPressHandler
searchKeyPressHandler
return error using typescript and I don't know how I can avoid it. searchKeyPressHandler
使用 typescript 返回错误,我不知道如何避免它。
document.addEventListener("keyup", function (e) { searchKeyPressHandler(appDispatch, e) });
could be a solution for addEventListener
可能是
addEventListener
的解决方案
but it is not useful for removeEventListener
because the event will be never removed with return () => document.removeEventListener("keyup", function (e) { searchKeyPressHandler(appDispatch, e) });
但它对
removeEventListener
没有用,因为事件永远不会被return () => document.removeEventListener("keyup", function (e) { searchKeyPressHandler(appDispatch, e) });
. .
Just wrap the actual event handler in an anonymous function and that function can then call your function with its arguments.只需将实际事件处理程序包装在匿名 function 中,然后 function 就可以使用其 ZDBC11CABDABDA8 调用您的 ZC1C425268E68385D1AB5074C17A94F142E977776。 But don't forget that event handlers are automatically passed a reference to the event that triggered them, so capture that in the outer handler and pass it along with your other arguments:
但是不要忘记事件处理程序会自动传递对触发它们的事件的引用,因此在外部处理程序中捕获它并将其与您的其他 arguments 一起传递:
document.addEventListener("keyup", function(event){ searchKeyPressHandler(event, x,y,z); });
Or, if you need to utilize the function that you are setting up as the "wrapper" more than once (in the case of having to remove the listener later), you'd just declare the function with a name and pass that name into .addEventListner()
as follows:或者,如果您需要多次使用您设置为“包装器”的 function(在以后必须删除侦听器的情况下),您只需使用名称声明 function 并将该名称传递给
.addEventListner()
如下:
function handler(event){
searchKeyPressHandler(event, x,y,z);
}
document.addEventListener("keyup", handler);
// And later...
document.removeEventListener("keyup", handler);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.