我正在尝试将onKeyPress
处理程序添加到我的应用程序中,以使其成为a11y
-compliant。我有一些交互式的<div />
元素,在这里它提出了一个问题。
我有下面的事件处理程序,我想在单击时触发它。
const handleViewInfoClick = (event: MouseEvent<HTMLDivElement> | KeyboardEvent<HTMLDivElement>): void => {
event.preventDefault();
onProfileClick();
window.open(withConfig(ConfigEnum.PROPERTY_PROFILE_URL, { propertyID: communityId }), '_blank');
};
我正在使用上述手柄作为:
<div
className={classes.community_name}
onClick={handleViewInfoClick}
onKeyDown={(e) => {
if (e.keyCode === 13) {
handleViewInfoClick(e);
}
}}
tabIndex={0}
role="button"
>
它会导致打字错误。
如果我声明event
为(event: MouseEvent | KeyboardEvent)
,类型记录抱怨handleViewInfoClick(e)
对参数的错误类型。如果我声明KeyboardEvent<HTMLDivElement>
,则handleViewInfoClick(e)
不会引发错误。然而,打字员抱怨说Type 'KeyboardEvent<HTMLDivElement>' is not generic
。
正确的处理方法是什么?
发布于 2021-12-31 17:49:55
对于React处理程序,您应该使用React中的事件类型,而不是DOM:
const handleViewInfoClick = (event: React.KeyboardEvent<HTMLDivElement> | React.MouseEvent<HTMLDivElement>): void => {
你也可以用
const handleViewInfoClick = (event: React.SyntheticEvent) => {
因为KeyboardEvent和MouseEvent都继承了SyntheticEvent,而您所关心的就是能够在它上调用preventDefault
,这是SyntheticEvent所拥有的。
https://stackoverflow.com/questions/70544528
复制相似问题