Setting default value of Material UI Autocomplete

好久不见. 提交于 2020-05-16 07:01:06

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!