我想从 React.js 中的 Material UI 向我的自动完成 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 下。还是行不通。
原文由 Etika49 发布,翻译遵循 CC BY-SA 4.0 许可协议
your
defaultValue
of<AutoComplete />
should have the same format as youroptions
, thegetOptionLable()
is used to form the label even from yourdefaultValue
。在您的代码中
title
字符串的属性是undefined
,因此未显示任何内容。这段代码应该可以正常工作: