如何获取选项 ID 而不是自动完成组件中显示的字符串?
How to get the option id instead of the shown string in the Autocomplete component?
我正在使用 React、material-ui 和 redux-form 做一个项目。长话短说:select 字段比我目前使用的字段,有时有很多选项,因此用户要求 select 搜索。
为此,我尝试使用 material 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;
我正在使用 React、material-ui 和 redux-form 做一个项目。长话短说:select 字段比我目前使用的字段,有时有很多选项,因此用户要求 select 搜索。
为此,我尝试使用 material 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;