简体   繁体   中英

how to capture event on select tab

I have used react-select for drop-drown feature in my application. I want to capture whether user has pressed the "Enter" button/key. I have done something like this:

render(){
 const props = {
  className: 'search-combobox',
  placeholder: "search something",
  onChange: this._onSelectionChange.bind(this),
  onSelect: this.props.onSelectedItem,
  options: this.state.options(),
  filterOptions: this._filterOptions.bind(this),
  onInputChange: this._onInputChange.bind(this),
  valueKey: 'id',
};

return(
<Select {...props}
  autoFocus={true}
  clearable={true}
  closeOnSelect={true}
  escapeClearsValue={true}
  onBlurResetsInput={false} />);
}

So on _onInputChange method, I tried this._onInputChange.bind(this, event). It didn't work. How to capture event then

Use onKeyDown prop on react-select to capture a key press event

<Select options={options} onKeyDown={onKeyDown} />

And check which key is pressed using event.keyCode (13 is for ENTER)

const onKeyDown = event => {
  if (event.keyCode === 13) {
    // enter has been pressed
  }
};

Working example: https://stackblitz.com/edit/react-stackoverflow-60219803

Above answer will work fine. I have attached link for keycodes incase if you want to change key.

https://keycode.info/

For enter it is 13.

Also bind required event according to below post.

onKeyPress Vs. onKeyUp and onKeyDown

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM