React,TypeScript:键入事件

时间:2019-06-13 06:02:44

标签: javascript reactjs typescript

问题在于在打字稿中正确键入事件

具有功能:

import * as React from 'react';

someHandler = (event: React.SyntheticEvent<HTMLInputElement> | React.KeyboardEvent<HTMLInputElement>) => {
  // event may be mouseclick or keypress
  // and to check if it is a keypress event i try to use instanceof.
  //
  // The logical way is to compare it with React.KeyboardEvent,

  if (event instanceof React.KeyboardEvent) {
    if (event.key === 'Enter') {
      // now i can access to event.key cause i know that event is keyboard event
    }
  }
  // but it throws error
  //
  // TS2339: Property 'KeyboardEvent' does not exist on typeof 'React'

  // ------

  // and as i expect i should compare it to KeyboardEvent
  //
  // that works
  if (event instanceof KeyboardEvent) {
    if (event.key === 'Enter') {
      // now i can access to event.key
    }
  }
};

但是问题是为什么它不那么明显地起作用? 我做错什么了吗?

谢谢!

0 个答案:

没有答案