使用MUI自动更正,选项由API填充



我几乎有一个可用的解决方案,但标签方面给出了一个未定义的错误,我还想确保我的解决方案是优雅的,因为它是一个我会经常重用的组件。

我有一个API,它返回一个json响应,为此,重要的值是;(我将去掉API,只提供它的响应(。

const countries = 
[
{ country_id: 1, name: 'France', iso: 'fr'},
{ country_id: 2, name: 'Germany', iso: 'de'},
{ country_id: 3, name: 'United Kingdom', iso: 'gb'},
{ country_id: 4, name: 'Spain', iso: 'es'}
];

这是一个MUI的例子,经过一些调整,它几乎可以按要求工作。

我希望"自动完成"中的标签是国家/地区名称,我希望返回的值是country_id,并且自动完成中的文本是他们选择的国家/地区的name。这是一个没有设定的标签。

const Select = ({ country, onUpdate }) => { 
//country is the valuable passed in to preselect an option or the option chosen, and the onUpdate is a function passed in (its a setState in the parent component).

const [countries, setCountries] = useState([]);
const [value, setValue] = React.useState('');
useEffect(() => {
api.get(`/countries`).then((response) => {
if (response.data) {
setCountries(response.data);
}
});
}, []);
return (
<>
<Autocomplete
autoHighlight
fullWidth
value={value}
options={countries}
onChange={(event, newValue) => {
setValue(newValue.name);
}}
inputValue={country}
onInputChange={(event, newInputValue) => {
onUpdate(newInputValue);
}}
renderOption={(props, country) => (
<Box component="li" {...props}>
{`{country.name} (${country.iso})`} 
</Box>
)}
renderInput={(params) => (
<TextField
{...params}
label="Choose a country"
/>
)}
/>
</>
);
};

Select.propTypes = {
country: PropTypes.string,
onUpdate: PropTypes.func.isRequired,
};
export default Select;

您需要将此行添加到自动完成属性中:

getOptionLabel={(option) => option.name}

根据文件:

选项结构
默认情况下,组件接受以下选项结构:

interface AutocompleteOption {
label: string;
}
// or
type AutocompleteOption = string;

例如:

const options = [
{ label: 'The Godfather', id: 1 },
{ label: 'Pulp Fiction', id: 2 },
];
// or
const options = ['The Godfather', 'Pulp Fiction'];

但是,您可以通过提供getOptionLabel道具来使用不同的结构。


另一个选项是将响应对象中的name属性更改为label,您将被设置。

最新更新