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

MUI Autocomplete组件如何在获取焦点时调用API?对应属性是什么?

在MUI Autocomplete组件获取焦点时调用API的实现方案

要实现Autocomplete获取焦点时调用API的需求,你需要通过**inputProps**传递onFocus事件处理函数——selectOnFocus属性仅用于自动选中输入框内容,和触发API请求无关,这就是你之前尝试无效的原因。

修改方案

在renderInput返回的TextField中,通过合并params.inputProps来添加自定义的onFocus回调:

  1. 先定义焦点触发的API调用函数:
const handleFocus = () => {
  // 在这里编写你的API调用逻辑,比如获取远程选项
  fetch('/api/your-endpoint')
    .then(res => res.json())
    .then(data => {
      // 更新选项列表,比如setRecentTimeTrackEntries(data)
    })
    .catch(err => console.error(err));
};
  1. 修改renderInput部分的代码,将onFocus注入到输入框的属性中:
renderInput={(params) => (
  <Stack direction="row" spacing={0.4}>
    <TextField
      onChange={handleChange}
      {...params}
      inputProps={{
        ...params.inputProps,
        onFocus: handleFocus // 添加焦点事件回调
      }}
    />
    {required ? <Typography variant="h4">*</Typography> : null}
  </Stack>
)}

完整修改后的组件代码

<Autocomplete
  id="entry-description"
  freeSolo
  selectOnFocus
  handleHomeEndKeys
  disableClearable
  onChange={handleSelection}
  options={recentTimeTrackEntries}
  inputValue={description}
  getOptionLabel={(option: any) => {
    return option.description;
  }}
  renderOption={(props, option) => {
    const optionLabel =
      `${option.description ? option.description : ''}${
        option.projectName
          ? (option.description ? ', ' : '') + option.projectName
          : ''
      }${
        option.tags.length
          ? option.tags.map((tag: FilteredTag) => tag.name).join(' ')
          : ''
      }` || '-';
    return (
      <li
        {...props}
        key={option.id}
        data-entry={JSON.stringify(option)}
        value={option.id}
      >
        {optionLabel}
      </li>
    );
  }}
  renderInput={(params) => (
    <Stack direction="row" spacing={0.4}>
      <TextField
        onChange={handleChange}
        {...params}
        inputProps={{
          ...params.inputProps,
          onFocus: () => {
            // 这里直接写API逻辑或者调用外部函数
            fetch('/api/your-endpoint')
              .then(res => res.json())
              .then(data => {
                // 更新选项状态
                // setRecentTimeTrackEntries(data);
              });
          }
        }}
      />
      {required ? <Typography variant="h4">*</Typography> : null}
    </Stack>
  )}
/>

补充说明

  • 如果需要避免重复触发API(比如用户多次快速点击焦点),可以在handleFocus中添加防抖逻辑,或者通过状态标记是否正在请求。
  • 若你希望在焦点触发时同时保留selectOnFocus的选中功能,不需要移除该属性,两者可以共存。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 10:02:28