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

新手上路,请多包涵

我想从 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 许可协议

阅读 308
2 个回答

your defaultValue of <AutoComplete /> should have the same format as your options , the getOptionLable() is used to form the label even from your 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" />}
/>

原文由 Yone 发布,翻译遵循 CC BY-SA 4.0 许可协议

您可以像这样使用 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" />}
/>

原文由 Dekel 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题