You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Material UI Autocomplete多选组件设置默认值后复选框未选中问题

问题原因及修正方案

你遇到的复选框未选中问题由以下几个代码错误导致,按优先级修正即可:

  • 缺少isOptionEqual属性配置,导致选中状态匹配失败
    MUI Autocomplete默认对对象类型的选项使用引用相等规则判断是否选中,你的consistenceUser数组中的用户对象和options属性传入的users数组中的用户对象如果不是同一个内存引用(比如是后端重新返回、或者深拷贝生成的新对象),就会导致组件判定为未选中,下拉框的复选框自然不会被勾选。
    你需要添加isOptionEqual prop,用唯一标识id来判断两个选项是否相等:
isOptionEqual={(a, b) => a.id === b.id}
  • 错误使用无效属性defaultChecked
    Autocomplete组件本身没有defaultChecked属性,这个属性对组件完全不生效,属于冗余代码可以直接删除。
  • renderTags用法不规范(不影响复选框选中,但建议修正)
    你当前在renderTags中直接使用外部的userValue变量,没有使用组件传入的选中值参数,如果你确实要保留该配置可以修改为:
renderTags={(selectedOptions) => renderUserValues(selectedOptions.map(item => item.id))}

另外注意handleUserChange回调中拿到的选中值是对象数组类型,如果你需要同步userValue(id数组),要自行做转换:

const handleUserChange = (e, newValue) => {
  setConsistenceUser(newValue)
  setUserValue(newValue.map(item => item.id))
}

修正后的完整组件代码

<Autocomplete
    multiple
    className={classes.select}
    disableCloseOnSelect
    options={users}
    value={consistenceUser}
    onChange={handleUserChange}
    // 新增id相等判断
    isOptionEqual={(a, b) => a.id === b.id}
    getOptionLabel={(option) => option.name}
    renderOption={(option, { selected }) => (
        <React.Fragment>
            <Checkbox
                icon={icon}
                checkedIcon={checkedIcon}
                style={{ marginRight: 8 }}
                checked={selected}
            />
            {option.name}
        </React.Fragment>
    )}
    renderTags={(selected) => renderUserValues(selected.map(i => i.id))}
    renderInput={(params) => (
        <TextField
            {...params}
            label={i18n.t("worklogModal.user")}
            variant="outlined"
        />
    )}
/>
<Typography className={classes.errorText}>
    {userError}
</Typography>

内容的提问来源于stack exchange,提问作者poPaTheGuru

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 16:12:02