zhongrj
2025-11-24 276323dce9613867abb3f58a4cc2abbfb2fd0dea
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import React from "react";
import { connect } from "formik";
 
class FormikErrorFocus extends React.Component {
    isObject(value) {
        return (
            value && typeof value === "object" && value.constructor === Object
        );
    }
    getKeysRecursively = object => {
        if (!this.isObject(object)) {
            return "";
        }
        const currentKey = Object.keys(object)[0];
        if (!this.getKeysRecursively(object[currentKey])) {
            return currentKey;
        }
        return currentKey + "." + this.getKeysRecursively(object[currentKey]);
    };
    componentDidUpdate(prevProps) {
        const { isSubmitting, isValidating, errors } = prevProps.formik;
        const keys = Object.keys(errors);
        if (keys.length > 0 && isSubmitting && !isValidating) {
            const selectorKey = this.getKeysRecursively(errors);
            const selector = `[id="${selectorKey}"], [name="${selectorKey}"] `;
            const errorElement = document.querySelector(selector);
            if (errorElement) errorElement.focus();
            console.warn(errors);
        }
    }
    render() {
        return null;
    }
}
export default connect(FormikErrorFocus);