Assigning default value to Autocomplete in MaterialUI and React.js

若如初见. 提交于 2021-01-28 09:56:20

问题


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

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