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

Material UI模态框中Formik表单首个Autocomplete组件autoFocus失效问题

问题根因

你自定义的Autocomplete组件内部给嵌套的TextField硬编码了autoFocus属性,所有调用该组件的位置都会默认触发自动聚焦,后渲染的Unit字段优先级更高,最终焦点就落在了Unit输入框上;同时你给Group字段加的autoFocus属性没有被透传到内部TextField,配置不生效。

解决方案

步骤1:修改自定义Autocomplete组件,改为透传autoFocus属性

将组件内部TextField写死的autoFocus改为从上层props取值,修改后的核心代码如下:

const NewAutocomplete: React.FC<
  FieldProps & {
    label?: string,
    options: Array<{ label: string, value: number }>,
    autoFocus?: boolean // 新增autoFocus属性声明
  }
> = ({ textFieldProps, field, form, label, options, isLoading, autoFocus, ...props }) => {
  // 其余原有逻辑不变
  const filterOptions = createFilterOptions({
    matchFrom: "start",
    limit: 500
  });
  const errorText =
    getIn(form.touched, field.name) && getIn(form.errors, field.name);

  const valueInit = [
    {
      value: 0,
      label: ""
    }
  ];
  return (
    <MuiAutocomplete
      {...props}
      {...field}
      filterOptions={filterOptions}
      options={[...valueInit, ...options]}
      getOptionLabel={(option) => (option ? option.label : "")}
      getOptionSelected={(option, value) => option.value === value?.value}
      style={{ width: 300 }}
      loading={isLoading}
      value={field.value}
      onChange={(e, value) => {
        form.setFieldValue(field.name, value);
      }}
      renderInput={(params) => (
        <TextField
          {...params}
          {...textFieldProps}
          label={label}
          helperText={errorText?.value || errorText}
          error={!!errorText}
          autoFocus={autoFocus} // 改为透传的autoFocus,不再写死
          InputProps={{
            ...params.InputProps,
            endAdornment: (
              <React.Fragment>
                {isLoading ? <CircularProgress color="primary" size={20} /> : null}
                {params.InputProps.endAdornment}
              </React.Fragment>
            )
          }}
        />
      )}
    />
  );
};

步骤2:确认字段配置

你原有MyForm里Group的Field已经加了autoFocus属性,保持该配置即可,Unit的Field不要添加autoFocus属性,这样只有Group的输入框会触发自动聚焦。

可选补充:处理Dialog默认焦点逻辑

如果修改后还是存在焦点偏移,可以给Popup组件里的Dialog添加disableAutoFocus={true}属性,禁用Material UI Dialog默认的自动焦点管理,避免组件内部逻辑抢焦点:

<Dialog
  {...rest}
  open={openPopup}
  maxWidth="sm"
  disableAutoFocus={true} // 新增该行配置
  classes={{ paper: classes.dialogWrapper }}
>

修改完成后打开模态框,焦点就会默认落在Group输入框上。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 20:45:00