问题
I would like to display default value to my Autocomplete TextField component from Material UI in React.js. A pre-populated value that is automatically loaded from the users' profile and that can be changed with another one from the list.
Here is my code:
import React from 'react';
import TextField from '@material-ui/core/TextField';
import Autocomplete from '@material-ui/lab/Autocomplete';
export const ComboBox =() => {
return (
<Autocomplete
id="combo-box-demo"
options={top100Films}
getOptionLabel={(option) => option.title}
style={{ width: 300 }}
renderInput={(params) => <TextField {...params} label="Combo box" defaultValue="The Godfather" variant="outlined" />}
/>
);
}
// Top 100 films as rated by IMDb users. http://www.imdb.com/chart/top
const top100Films = [
{ title: 'The Shawshank Redemption', year: 1994 },
{ title: 'The Godfather', year: 1972 },
{ title: 'The Godfather: Part II', year: 1974 },
{ title: 'The Dark Knight', year: 2008 }
]
I only see the input field with the label on it. defaultValue is listed as an API of both TextField and Autocomplete and I also tried to move it directly under Autocomplete. Still not working.
回答1:
your defaultValue of <AutoComplete /> should have the same format as your options, the getOptionLable() is used to form the label even from your defaultValue.
in your code title property of the string is undefined, so nothing is shown.
this should work fine:
<Autocomplete
id="combo-box-demo"
options={top100Films}
defaultValue={{ title: "The Godfather", year: 1972 }}
getOptionLabel={(option) => option.title}
style={{ width: 300 }}
renderInput={(params) => <TextField {...params} label="Combo box" defaultValue="The Godfather" variant="outlined" />}
/>
回答2:
You can use the defaultValue option like this:
<Autocomplete
id="combo-box-demo"
options={top100Films}
defaultValue={ top100Films[0] }
getOptionLabel={(option) => option.title}
style={{ width: 300 }}
renderInput={(params) => <TextField {...params} label="Combo box" defaultValue="The Godfather" variant="outlined" />}
/>
来源:https://stackoverflow.com/questions/61213634/assigning-default-value-to-autocomplete-in-materialui-and-react-js