问题
I am trying to set the initial value of the Autocomplete to "ACCU-SEAL 35-532 Bag Sealer" but get the following error:
Material-UI: the 'getOptionLabel' method of Autocomplete returned undefined instead of a string for "ACCU-SEAL 35-532 Bag Sealer".
so I tried to add the following to my Autocomplete:
getOptionSelected={(option, value) => option.label === value}
but I get the same error.
I have an example of my code up here: https://codesandbox.io/s/material-demo-fv075?file=/formElementsEdit.jsx
Any help in setting the initial value of the autocomplete would be greatly appriciated.
回答1:
When you use have options
in the Autocomplete, you should use the same values that your options contains.
In your examples each option is an object with value
and label
. Since you use that label
in the getOptionLabel
function - you should use at least the label
in the object that you are passing.
Option #1:
const value = "ACCU-SEAL 35-532 Bag Sealer";
...
<Autocomplete
...
value={{label: value}}
Option #2:
const value = "ACCU-SEAL 35-532 Bag Sealer";
...
<Autocomplete
...
value={{label: value, value: 1}}
Option #3: ...
In any of the above options - the value of the property value
should be an object with at least one key - the label
key.
Check the following example based on your code: https://codesandbox.io/s/material-demo-zzfh7?file=/formElementsEdit.jsx
来源:https://stackoverflow.com/questions/61418401/setting-default-value-of-material-ui-autocomplete