Mui 自动完成功能在失去焦点时不触发更改

Mui Autocomplete not firing onChange when losing focus

提问人:pancake 提问时间:11/6/2023 更新时间:11/6/2023 访问量:33

问:

使用带有 和 的 Mui 时,按 Return 键会触发事件。但是,按 Tab 键退出“自动完成”小组件不会,用户键入的文本仍然存在,而自动完成本身的状态尚未更新(仅更新自动完成中的状态)。AutocompletemultiplefreeSoloonChangeTextField

  // Called when return is pressed
  function onAddNewItem(e, items) {
    console.log("Validation code goes here");
    setItems(items);
  }

  // Called on a keystroke for the text currently being typed
  function onInputChange(e, newItem) {
    setInputValue(newItem);
  }

  return (
    <Autocomplete
      multiple
      freeSolo
      disableClearable
      options={[]}
      value={items}
      onChange={onAddNewItem}
      inputValue={inputValue}
      onInputChange={onInputChange}
      renderInput={(params) => (
        <TextField {...params} error={error} placeholder="Type here" />
      )}
    />
  );

查看 codesandbox

如何触发触发,或以其他方式将自动完成状态设置为失去焦点?使用没有帮助,因为我没有从更新的自动完成中传递“草稿”项,因此无法设置新的自动完成状态。onChangeonBlur

JavaScript Material-UI 自动完成

评论


答:

1赞 Usama 11/6/2023 #1

您需要在自动完成中设置 autoSelect

<Autocomplete
  ....
  autoSelect={true}
/>

评论

1赞 pancake 11/7/2023
太棒了 - 这成功了,谢谢!