javascript - 在 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 下。还是行不通。
解决方案
你defaultValue
的<AutoComplete />
应该与你的格式相同options
,getOptionLable()
即使是从你的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" />}
/>
推荐阅读
- flutter - Listview搜索在列表中找不到数据
- react-native - Expo React Native 项目的 Axios 配置中未设置环境变量
- list - 生成代表门铃系统的列表
- python - 使用以下几种格式的正则表达式提取日期
- android - Android Web 视图未加载此静态 Html
- pandas - Dask - 如何节省内存,例如通过部分读取 csv?
- c++ - 有没有办法在 c++ 中确定标准输入内容的大小(以字节为单位)?
- postgresql - 如何为 postgresql db 创建多个列分区,一个用于时间范围,一个用于特定传感器 ID?
- javascript - 旋转 div 然后扩展
- angular - 获取值后来自订阅的 Angular/Typescript 处理结果