[英]How do I get an event when any option is selected for a Material UI Autocomplete React component?
[英]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.