【问题标题】:Typescript/React what's the correct type of the parameter for onKeyPress?Typescript/React onKeyPress 的正确参数类型是什么?
【发布时间】:2018-03-09 19:48:17
【问题描述】:

Typescript 2.3.4、react 15.5.4 和 react-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: Enter,但e 的类型应该是什么,以便我可以将值与(什么?)进行比较,以判断是否按下了 Enter。

【问题讨论】:

标签: reactjs typescript react-bootstrap


【解决方案1】:

onKeyPress的类型应该是KeyboardEventHandler&lt;T&gt;,可以写成以下两种方式之一:

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

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

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

请注意,keyCode 可作为 e 上的属性直接使用;您无需通过nativeEvent 访问它。

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

【讨论】:

  • 我看不出你的类型声明如何让我在不强制转换的情况下访问我想要的数据?看我的回答。
  • 你说得对,我已经编辑以改进我的答案。其中一些现在与您的非常相似,但希望其中还有一些额外有用的东西。
【解决方案2】:

这似乎有效:

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

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

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

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

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

【讨论】:

  • 如果你想简单地指定 KeyBoardEvent,你必须从 React 中导入它,仅此而已。 import {KeyboardEvent} from 'react';
猜你喜欢
  • 2019-05-10
  • 2020-06-07
  • 2011-04-16
  • 2019-04-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-29
相关资源
最近更新 更多