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

MUI Autocomplete组件无法接受文本框输入的非下拉选项值问题

解决MUI Autocomplete无法接受自定义输入值的问题

问题原因

  1. 组件value绑定的是字符串类型的row.client_id,但options中的选项是对象(如{client_id: 'abcd'}),freeSolo模式下输入的自定义值为字符串,类型不匹配导致组件无法正确识别和显示。
  2. onChangeTableInput处理client_id时,默认尝试获取keyValue.client_id,但自定义输入的字符串没有该属性,导致赋值失败。
  3. 未配置getOptionLabel,Autocomplete无法正确解析选项的显示文本。

修改方案

1. 调整Autocomplete组件配置

添加类型兼容的getOptionLabel,适配value的类型,同时确保自定义值能被显示和选中:

<Autocomplete
  disabled={row.group_mapping_id && !('editClicked' in row)}
  freeSolo
  // 适配value:如果是字符串直接使用,否则匹配对应选项
  value={typeof row.client_id === 'string' 
    ? row.client_id 
    : props.clientIds.find(opt => opt.client_id === row.client_id) || row.client_id}
  onChange={(event, newValue) => props.onChangeTableInput('client_id', index, newValue, row)}
  selectOnFocus
  clearOnBlur
  handleHomeEndKeys
  options={props.clientIds}
  // 兼容对象和字符串类型的选项文本
  getOptionLabel={(option) => typeof option === 'string' ? option : option.client_id || ''}
  renderOption={(props, option) => <li {...props}>{option.client_id || option}</li>}
  autoHighlight
  style={{width: '110px'}}
  disableClearable
  // 确保自定义输入值出现在下拉列表中
  filterOptions={(options, params) => {
    const filtered = options.filter(opt => opt.client_id.includes(params.inputValue));
    if (params.inputValue && !filtered.some(opt => opt.client_id === params.inputValue)) {
      filtered.push(params.inputValue);
    }
    return filtered;
  }}
  renderInput={(params) => <TextField {...params} 
    variant='outlined'
    inputProps={{
      ...params.inputProps,
      autoComplete: "disabled",
      type: 'search'
    }} />}
/>

2. 修改onChangeTableInput函数

增加类型判断,分别处理自定义字符串和选中的选项对象:

const onChangeTableInput = (keyName, index, keyValue, rowData) => {
  let temp_array = [...props.groupTableData];
  if(keyName === 'client_id'){
    // 区分字符串和对象类型的输入值
    temp_array[index][keyName] = typeof keyValue === 'string' 
      ? keyValue 
      : keyValue.client_id;   
  }else if(keyName === 'client_name'){
    temp_array[index][keyName] = typeof keyValue === 'string' 
      ? keyValue 
      : keyValue.client_name;
  }else{
    temp_array[index][keyName] = keyValue;
  }
  if (rowData && !rowData.group_mapping_id) {
    temp_array[index]['operation'] = 'N';
  }
  props.setGroupTableData(temp_array);
};

说明

  • getOptionLabel:明确组件如何将选项(包括自定义字符串)转换为显示文本,解决类型不匹配问题。
  • value适配:确保组件内部状态与绑定的row.client_id类型一致,避免显示异常。
  • filterOptions:将自定义输入值加入下拉列表,提升用户操作体验。
  • 类型判断:避免自定义字符串访问client_id属性导致的错误,确保数据正确更新。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 10:03:22