如何将 onchange 与自动完成材料 ui 一起使用?

Emm*_*Emm 7 autocomplete reactjs material-ui react-hooks

使用方法 handleChange 处理带有 Hooks 样式的 Form Input 的 OnChange 事件,该样式设置对象的状态。

handleChange 函数依次调用 setLocation,后者使用新值更新位置状态。

为了使用户数据输入更容易,我决定将城市字段更改为自动完成,但我未能捕获自动完成的值。在文档中,他告诉我我需要传递两个参数,但我不太明白

function(event: object, value: any) => void
event: The event source of the callback
value: null
Run Code Online (Sandbox Code Playgroud)

如何访问字段的值并将其放入我的函数中以插入数据?

        <Autocomplete
        style={{ width: 300 }}
        value={location.City}
        onChange={handleChange}
        options={list.City}
        classes={{
          option: classes.option,
        }}
        autoHighlight
        getOptionLabel={option => typeof option === 'string' ? option : option.City}
        renderOption={option => (
          <React.Fragment>

            {option.City} -{option.State}
          </React.Fragment>
        )}

         renderInput={params => (
           <TextField {...params} label="City"  value={location.City}  margin="normal" variant="outlined" style={{ width: 220 }} inputProps={{
             ...params.inputProps,
             autoComplete: 'disabled', // disable autocomplete and autofill
           }}/>
         )}
       />
Run Code Online (Sandbox Code Playgroud)

Bar*_*000 12

如果您只是想在用户键入时获取输入值,则需要使用onInputChange. 该onChange处理器运行在用户选择从下拉选项。

export default function ComboBox() {
  function handleInputChange(event, value) {
    console.log(value);
  }

  return (
    <Autocomplete
      id="combo-box-demo"
      options={top100Films}
      getOptionLabel={(option: FilmOptionType) => option.title}
      style={{ width: 300 }}
      onInputChange={handleInputChange}
      renderInput={params => (
        <TextField {...params} label="Combo box" variant="outlined" fullWidth />
      )}
    />
  );
}
Run Code Online (Sandbox Code Playgroud)

代码沙盒