首页 > 解决方案 > 在 MaterialUI 和 React.js 中为 Autocomplete 分配默认值

问题描述

我想从 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 下。还是行不通。

标签: javascriptreactjsmaterial-ui

解决方案


defaultValue<AutoComplete />应该与你的格式相同optionsgetOptionLable()即使是从你的defaultValue.

在字符串的代码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" />}
/>

推荐阅读