简体   繁体   中英

Single handler for ReactJS onClick and onKeyDown events for TypeScript

I am trying to add onKeyPress handlers to my application to make it a11y -compliant. I have some interactive <div /> elements, where it is presenting a problem.

I have the following event handlers to I want to fire on click.

const handleViewInfoClick = (event: MouseEvent<HTMLDivElement> | KeyboardEvent<HTMLDivElement>): void => {
  event.preventDefault();
  onProfileClick();
  window.open(withConfig(ConfigEnum.PROPERTY_PROFILE_URL, { propertyID: communityId }), '_blank');
};

I am using the above hanlder as:

<div
  className={classes.community_name}
  onClick={handleViewInfoClick}
  onKeyDown={(e) => {
    if (e.keyCode === 13) {
      handleViewInfoClick(e);
    }
  }}
  tabIndex={0}
  role="button"
>

It results in typescript errors.

If I declare event as (event: MouseEvent | KeyboardEvent) , typescript complaints that handleViewInfoClick(e) is getting a wrong type for an argument. If I declare KeyboardEvent<HTMLDivElement> , the handleViewInfoClick(e) is not raising errors. However, typescript complaints that Type 'KeyboardEvent<HTMLDivElement>' is not generic .

What is the correct way to handle this?

With React handlers, you should use the event typings from React, not from the DOM:

const handleViewInfoClick = (event: React.KeyboardEvent<HTMLDivElement> | React.MouseEvent<HTMLDivElement>): void => {

You could also use

const handleViewInfoClick = (event: React.SyntheticEvent) => {

because both KeyboardEvent and MouseEvent inherit from SyntheticEvent, and all you care about is being able to call preventDefault on it, which SyntheticEvent has.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM