簡體   English   中英

如何在自動完成組件中獲取選項 ID 而不是顯示的字符串?

[英]How to get the option id instead of the shown string in the Autocomplete component?

我正在使用 React、material-ui 和 redux-form 做一個項目。 長話短說:比我目前使用的選擇字段,有時有很多選項,所以用戶要求選擇帶有搜索。

為了做到這一點,我正在嘗試使用材料 ui 的實驗室部分中的自動完成組件:

<Autocomplete
      options={options}
      style={{ width: '80%', padding: '10px '}}
      getOptionLabel={ options => (options.nombres +" "+options.apellidos) }
      renderOption={ (options, status) => {
        return (options.nombres + " " + options.apellidos)
      }}
      renderInput={params => { console.log(params); return(<TextField 
        { ...params} 
        label={label}
        fullWidth
    />)}}

這里的問題是,當我提交表單時,該字段的值是我使用 getOptionLabel 顯示的字符串,但我需要顯示名稱,但在提交表單時獲取值 Id ..伙計們可以幫我解決這個問題。

我為此使用鈎子:

const Sample = () => {
  const [autocomplete, setAuto] = React.useState(null);

  const handleAutocomplete = (event, newValue) => {
    if (newValue != null) {
    console.log(newValue.id)
    setAuto(newValue);
    }
  }


  return (
    <Autocomplete
          options={options}
          style={{ width: '80%', padding: '10px '}}
          getOptionLabel={ options => (options.nombres +" "+options.apellidos) }
          onChange={handleAutocomplete}
          renderInput={params => ( <TextField
            { ...params}
            label="Selecciona..."
            fullWidth/>
          )}
          />
        );
};

const options = [
  {
  nombres: 'Juan García',
  apellidos: 'Oliver',
  id: 1,
  },
  {
  nombres: 'Melchor',
  apellidos: 'Martínez',
  id: 2,
  },
  {
  nombres: 'Ricardo',
  apellidos: 'Sanz',
  id: 3,
  },
]


export default Sample;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM