在MaterialUI和React.js中为自动完成分配默认值

时间:2020-04-14 17:25:52

标签: javascript reactjs material-ui

我想在React.js的Material UI中为我的Autocomplete TextField组件显示默认值。从用户的配置文件自动加载的预填充值,可以使用列表中的另一个值进行更改。

这是我的代码:

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 } 
]

我只看到带有标签的输入字段。 defaultValue被列为TextField和Autocomplete的API,我也尝试将其直接移到Autocomplete下。还是行不通。

2 个答案:

答案 0 :(得分:2)

defaultValue中的<AutoComplete />应该与您的options相同,getOptionLable()用于形成标签,即使您来自defaultValue。 / p>

您字符串的代码title的属性为undefined,因此什么也没有显示。

这应该很好:

<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" />}
/>

答案 1 :(得分:1)

您可以像这样使用defaultValue选项:

<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" />}
/>