关于reactjs:在React中键入检查onKeyPress事件的正确方法是什么?

What is the right way to type check an event onKeyPress in React?

以下代码:

1
2
3
4
5
6
7
8
9
10
  <input
    type="text"
    onKeyPress={(e) => addTag(e)}
  />

  const addTag = (e: React.SyntheticEvent<HTMLInputElement>): void => {
    if (e.key === 'Enter')) {
      // Do something with `e.currentTarget.value`
    }
  };

它导致此错误:

1
Property 'key' does not exist on type 'SyntheticEvent<HTMLInputElement, Event>'.

如何在此处输入活动?无论使用什么,都必须与e.currentTarget.value

一起使用。


React输入的

onKeyPress事件具有以下类型:
(event: React.KeyboardEvent<HTMLInputElement>) => void

类型定义:https://github.com/facebook/react/blob/4cb399a433771c84e861d5ca3d38a24733d23ad8/packages/react-interactions/events/src/dom/Keyboard.js#L36