繁体   English   中英

如何在自动完成中设置默认选择项

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM