[英]How to set default selected items in Autocomplete
我正在使用 material-ui 自動完成,我想向它添加一些默認選擇的選項。
https://codesandbox.io/s/broken-fire-htxtd?file=/src/App.js
正如您在示例中看到的,我正在使用 startAdornment 渲染預選項目。 問題是當我嘗試 select 另一個項目時,它會自動刪除預先選擇的項目。 我也無法正確刪除它們。
這個想法是這個默認選擇保持選中狀態,直到我刪除它們。 還能夠選擇另一個字母而不刪除它們。
您可以使用defaultValue
屬性而不是裝飾。
<Autocomplete
multiple
open={open}
onOpen={() => {
setOpen(true);
}}
onClose={() => {
setOpen(false);
}}
options={["A", "B", "C", "D", "E"]}
disableCloseOnSelect
defaultValue={cities} //here
onChange={(e, v) => setCities(v)}
getOptionLabel={(option) => option}
renderOption={(option, { selected }) => {
if (cities.includes(option)) {
selected = true;
}
return (
<React.Fragment>
<Checkbox
icon={icon}
checkedIcon={checkedIcon}
style={{ marginRight: 8 }}
checked={selected}
/>
{option}
</React.Fragment>
);
}}
renderInput={(params) => {
return (
<TextField
{...params}
variant="outlined"
label="Cities"
placeholder="Enter cities"
autoComplete="off"
/>
);
}}
/>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.