Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

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

Typescript 2.3.4, react 15.5.4 and react-bootstrap 0.31.0.

I have a FormControl and I want to do something when the user presses enter.

The control:

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

What should the definition of the parameter for handleKeywordKeypress be?

I can define it like this:

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This seems to work:

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

The key(Ha ha) here, for me, was to specify React.KeyboardEvent, rather than KeyboardEvent.

Trolling around the React code, I was seeing definitions like:

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

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...