Typescript/React onKeyPress 的正确参数类型是什么?

Typescript/React what's the correct type of the parameter for onKeyPress?

打字稿 2.3.4,反应 15.5.4 和反应-bootstrap 0.31.0.

我有一个 FormControl 并且我想在用户按下回车键时做一些事情。

控件:

<FormControl
  name="keyword"
  type="text"
  value={this.state.keyword}
  onKeyPress={this.handleKeywordKeypress}
  onChange={(event: FormEvent<FormControlProps>) =>{
    this.setState({
      keyword: event.currentTarget.value as string
    });
  }}
/>

handleKeywordKeypress的参数定义应该是什么?

我可以这样定义:

handleKeywordKeypress= (e: any) =>{
  log.debug("keypress: " + e.nativeEvent.code);
};

这将被调用,它会打印 keypress: Entere 的类型应该是什么,以便我可以将值与(什么?)进行比较以判断是否按下了 Enter。

onKeyPress的类型应该是KeyboardEventHandler<T>,可以写成以下任意一种:

handleKeywordKeypress: KeyboardEventHandler<FormControl> = e => {
    // use e.keyCode in here
}

import { KeyboardEvent } from "react";
handleKeywordKeypress = (e: KeyboardEvent<FormControl>) => {
    // use e.keyCode in here
};

正如您在回答中指出的那样,如果您选择第二个选项,则需要专门使用 React 中的 KeyboardEvent

请注意,keyCodee 上可直接作为 属性 使用;您不需要通过 nativeEvent.

访问它

此外,通用类型参数 T 应该是 FormControl 组件,而不是它的 props,因此您也应该更改其他处理程序。

这似乎有效:

handleKeywordKeyPress = (e: React.KeyboardEvent<FormControl>) =>{
  if( e.key == 'Enter' ){
    if( this.isFormValid() ){
      this.handleCreateClicked();
    }
  }
};

关键(呵呵)这里对我来说是指定React.KeyboardEvent,而不是KeyboardEvent

浏览 React 代码,我看到如下定义:

type KeyboardEventHandler<T> = EventHandler<KeyboardEvent<T>>;

但没有意识到当我将 copy/pasting KeyboardEvent 作为我的处理程序的参数类型时,编译器实际上选择了 KeyboardEvent 这是某种默认值在某处的 Typescript 库中定义的类型(而不是 React 定义)。

以上两个答案都没有解决我的问题,应该很简单明了:

import { KeyboardEvent } from 'react';

const handleKeyPress = (e: KeyboardEvent<HTMLInputElement>) => {
   // do stuff
};