问题描述
Typescript 2.3.4,react 15.5.4 和 react-bootstrap 0.31.0.
Typescript 2.3.4, react 15.5.4 and react-bootstrap 0.31.0.
我有一个 FormControl
,我想在用户按下 Enter 键时做一些事情.
I have a FormControl
and I want to do something when the user presses enter.
控制:
<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
的参数定义应该是什么?
What should the definition of the parameter for handleKeywordKeypress
be?
我可以这样定义:
handleKeywordKeypress= (e: any) =>{
log.debug("keypress: " + e.nativeEvent.code);
};
这将被调用,它将打印 kepress: Enter
但是 e
的类型应该是什么,以便我可以将值与(什么?)进行比较判断是否按下了 Enter.
That will be called, and it will print kepress: Enter
but what should the type of e
be so that I can compare the value against (what?) to tell if Enter was pressed.
推荐答案
这似乎有效:
handleKeywordKeyPress = (e: React.KeyboardEvent<FormControl>) =>{
if( e.key == 'Enter' ){
if( this.isFormValid() ){
this.handleCreateClicked();
}
}
};
这里的关键,对我来说,是指定React.KeyboardEvent
,而不是KeyboardEvent
.
The key here, for me, was to specify React.KeyboardEvent
, rather than KeyboardEvent
.
浏览 React 代码,我看到如下定义:
Trolling around the React code, I was seeing definitions like:
type KeyboardEventHandler<T> = EventHandler<KeyboardEvent<T>>;
但是没有意识到当我复制/粘贴 KeyboardEvent
作为我的处理程序的参数类型时,编译器实际上选择了某种类型的 KeyboardEvent
在某个地方的 Typescript 库中定义的默认类型(而不是 React 定义).
But didn't realise that when I was copy/pasting KeyboardEvent
as the parameter type for my handler, the compiler was actually picking up the KeyboardEvent
which is some kind of default type defined in the Typescript libraries somewhere (rather than the React definition).
这篇关于Typescript/React onKeyPress 参数的正确类型是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!