简体   繁体   中英

How do I get an event when any option is selected for a Material UI Autocomplete React component?

I have an autocomplete. I need to intercept when an option is selected. The onChange event I have bound works only when the selection, is different than the last one. I just want to know whenever one is selected, period. I can think of a few strategies for this, none of which seem to be provisioned by the Autocomplete API.

  1. Just catch an event whenever something is selected. This doesn't exist that I know of.
  2. Always set the "current selected" option to null so everything is a change. This doesn't exist that I know of.
  3. Maybe some custom options rendering that encompasses all of the interaction logic that I am trying to avoid by using the Material UI control...is this the only way?
    <Autocomplete
        className={classes.textfield}
        id={entityId}
        freeSolo
        open={showSuggestions}
        onClose={handlePopoverClose}
        onChange={handleOptionSelected}
        options={options} 
        filterOptions={(options, state) => options}
        renderInput={(params) => (
          <TextField inputRef={textfieldRef} {...params} id={entityId} margin="normal" 
               onKeyPress={handleKeyPress} onInput={handleInputChanged} value={controlText}/>
        )}
      />

According to the material ui documentation , you can actually filter out the type of onChange event by accessing the second optional parameter ( reason ).

This is how you can check when any of the options are selected:

const handleOptionSelected = (event,value, reason) => {
  if (reason === 'select-option') {
    // do the rest
  };
};

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