[英]Assigning default value to Autocomplete in MaterialUI and 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 }
]
我只看到帶有 label 的輸入字段。 defaultValue 被列為 TextField 和 Autocomplete 的 API,我還嘗試將其直接移動到 Autocomplete 下。 還是行不通。
您的<AutoComplete />
的defaultValue
應該與您的options
具有相同的格式,即使從您的defaultValue
也可以使用getOptionLable()
來形成 label 。
在您的代碼中,字符串的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" />}
/>
您可以像這樣使用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" />}
/>
如果你使用多個,那么你應該像下面這樣在列表中設置 defaultValue
<Autocomplete multiple id="tags-standard" options={categoryList}
defaultValue={[{ title: "cat1", id: 1 }, { title: "cat2", id: 2 }]}
getOptionLabel={(option) => option.title}
renderInput={(params) => (
<TextField {...params} variant="standard" label="Category" />
)}
onChange={handleCategory}
/>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.