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

如何在react-admin 4.x中聚焦首个验证失败字段

在React Admin 4.x中实现首个验证失败字段自动聚焦

React Admin 4.x弃用了Final Form,改用react-hook-form,因此无法再直接使用final-form-focus。你可以通过react-hook-form的API结合React Admin的表单上下文来实现相同功能,具体步骤如下:

1. 封装自定义Hook处理错误聚焦

创建一个可复用的Hook,利用useFormContext获取react-hook-form的表单状态和方法,监听错误变化并聚焦首个错误字段:

import { useEffect } from 'react';
import { useFormContext } from 'react-hook-form';

export const useFocusFirstError = () => {
  const { setFocus, formState: { errors } } = useFormContext();

  // 处理嵌套字段的错误查找逻辑(可选,根据你的表单结构决定)
  const findFirstErrorKey = (errorObj) => {
    for (const key in errorObj) {
      if (errorObj[key]) {
        // 若当前字段存在嵌套错误,递归查找
        if (errorObj[key].errors) {
          const nestedKey = findFirstErrorKey(errorObj[key].errors);
          return nestedKey ? `${key}.${nestedKey}` : key;
        }
        return key;
      }
    }
    return null;
  };

  useEffect(() => {
    const firstErrorKey = findFirstErrorKey(errors);
    // 存在错误字段时触发聚焦
    if (firstErrorKey) {
      setFocus(firstErrorKey);
    }
  }, [errors, setFocus]);
};

2. 在React Admin表单中使用该Hook

在你的SimpleForm、TabbedForm等表单组件内部引入并使用这个Hook,确保它能获取到正确的表单上下文:

import { Edit, SimpleForm, TextInput, required } from 'react-admin';
import { useFocusFirstError } from './useFocusFirstError';

const UserEdit = () => {
  return (
    <Edit>
      <SimpleForm>
        <TextInput source="name" validate={required("请输入姓名")} />
        <TextInput source="email" validate={required("请输入邮箱")} />
        {/* 直接调用Hook即可自动处理错误聚焦 */}
        {useFocusFirstError()}
      </SimpleForm>
    </Edit>
  );
};

export default UserEdit;

注意事项

  • 确保表单字段的source属性值与react-hook-form注册的字段名完全一致,这是errors对象的键值来源。
  • 若你的表单包含嵌套字段(如source="profile.address"),上述Hook中的递归查找逻辑可以正确识别并聚焦对应的嵌套字段。
  • 该Hook会在表单错误状态变化时自动触发,无论是提交表单时的验证失败,还是用户输入过程中的实时验证错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 15:57:15