Getting the value in the React material-UI Autocom

2020-06-30 05:51发布

问题:

I am referring to the documentation of React Material-UI (https://material-ui.com/components/autocomplete/).

In the demo code,

    <Autocomplete
      options={top100Films}
      getOptionLabel={(option: FilmOptionType) => option.title}
      style={{ width: 300 }}
      renderInput={params => (
        <TextField {...params} label="Combo box" variant="outlined" fullWidth />
      )}
    />

I get how it works, but I am not sure how I am supposed to get the selected value.

For example, I want to use the onChange prop to this so that I can make some actions based on the selection.

I tried adding onChange={v => console.log(v)}

but the v does not show anything related to the selected value.

回答1:

Solved by using passing in the (event, value) to the onChange props.

<Autocomplete
    onChange={(event, value) => console.log(value)} // prints the selected value
    renderInput={params => (
        <TextField {...params} label="Label" variant="outlined" fullWidth />
    )}
/>