无法使用InnerRef禁用外部formik的按钮

发布于 2025-01-21 15:39:14 字数 5884 浏览 0 评论 0原文

我正在尝试使用formik中的InnerRef在Formik之外获取Isvalid and Dirty,以禁用提交按钮。我已经附上了下面的编码。

import React, { useRef } from "react";
import { Button, Checkbox, Select } from "antd";
import { useTranslation } from "react-i18next";
import { OverlayScrollbarsComponent } from "overlayscrollbars-react";
import { Formik, Form, Field, ErrorMessage } from "formik";
import * as Yup from "yup";
import { FloatLabel } from "../../../UIComponent/index";
import { roles } from "../../Roles/sample";
import { filter, sort } from "../../../_util/select";

const AddEditUser = ({ setVisible, visible, users }) => {
    const { t } = useTranslation();
    const { Option } = Select;
    let formRef = useRef({});

    const userValidationSchema = Yup.object().shape({
        firstName: Yup.string().required("First Name is Required."),
        userName: Yup.string().required("User Name is Required.")
            .test("username-unique", "User Name Already Exist.",
                (value) => users.find(el => el.name?.toLowerCase() === value?.toLowerCase()) ? false : true),
        password: Yup.string().required("Password is Required.")
    });

    return <div className="formContainer h-100">
        <OverlayScrollbarsComponent className="formBody">
            <Formik
                innerRef={formRef} 
                initialValues={{
                    firstName: "",
                    lastName: "",
                    userName: "",
                    role: "",
                    password: ""
                }}
                validationSchema={userValidationSchema}
                onSubmit={async values => { }}
                onChange={()=> console.log("sss")}
            >
                {({
                    values,
                    setFieldValue,
                    setFieldTouched,
                    errors,
                    touched
                }) => <Form noValidate>
                        <div className="innerContainer row">
                            <div className="col-12 mb-2 ">
                                <FloatLabel label="First Name" name="firstName" value={values.firstName}>
                                    <Field
                                        type="text"
                                        className="w-100 form-control"
                                        name="firstName" />
                                    <ErrorMessage
                                        name="firstName"
                                        component="span"
                                        className="errorMessage"
                                    />
                                </FloatLabel>
                            </div>
                            <div className="col-12 mb-2">
                                <FloatLabel label="Last Name" name="lastName" value={values.lastName}>
                                    <Field
                                        type="text"
                                        className="w-100 form-control"
                                        name="lastName" />
                                    <ErrorMessage
                                        name="lastName"
                                        component="span"
                                        className="errorMessage"
                                    />
                                </FloatLabel>
                            </div>
                            <div className="col-12 mb-2">
                                <FloatLabel label="User Name" name="userName" value={values.userName}>
                                    <Field
                                        type="text"
                                        className="w-100 form-control"
                                        name="userName" />
                                    <ErrorMessage
                                        name="userName"
                                        component="span"
                                        className="errorMessage"
                                    />
                                </FloatLabel>
                            </div>
                       
                            <div className="col-12 mb-2">
                                <FloatLabel label="Password" name="password" value={values.password}>
                                    <Field
                                        type="password"
                                        className="w-100 form-control"
                                        name="password" />
                                    <ErrorMessage
                                        name="password"
                                        component="span"
                                        className="errorMessage"
                                    />
                                </FloatLabel>
                            </div>
                    </Form>
                }
            </Formik>

        </OverlayScrollbarsComponent>
        <footer>
            <Button className="button"
                disabled={!(formRef.isValid && formRef.dirty)}>
                {t("submit")}
            </Button>
        </footer>
    </div>
};

export default AddEditUser;

在上面的示例中,IM使用InnerRef在Formik中使用InnerRef将其属性从表单中取出以禁用按钮,但无法按预期工作。我尝试将控制台放入InnerRef中,看到该值正在更新

   innerRef={(ref)=> {
     console.log(ref);  // here I'm seeing the value updating whenever the form properties 
                           value changes
     formRef = ref;

   }}

,但没有禁用按钮。有人可以帮助如何从formik中获取属性以禁用提交按钮

I'm trying to use innerRef in Formik to get the isValid and dirty outside the Formik to disable the submit button. I have attached the coding below.

import React, { useRef } from "react";
import { Button, Checkbox, Select } from "antd";
import { useTranslation } from "react-i18next";
import { OverlayScrollbarsComponent } from "overlayscrollbars-react";
import { Formik, Form, Field, ErrorMessage } from "formik";
import * as Yup from "yup";
import { FloatLabel } from "../../../UIComponent/index";
import { roles } from "../../Roles/sample";
import { filter, sort } from "../../../_util/select";

const AddEditUser = ({ setVisible, visible, users }) => {
    const { t } = useTranslation();
    const { Option } = Select;
    let formRef = useRef({});

    const userValidationSchema = Yup.object().shape({
        firstName: Yup.string().required("First Name is Required."),
        userName: Yup.string().required("User Name is Required.")
            .test("username-unique", "User Name Already Exist.",
                (value) => users.find(el => el.name?.toLowerCase() === value?.toLowerCase()) ? false : true),
        password: Yup.string().required("Password is Required.")
    });

    return <div className="formContainer h-100">
        <OverlayScrollbarsComponent className="formBody">
            <Formik
                innerRef={formRef} 
                initialValues={{
                    firstName: "",
                    lastName: "",
                    userName: "",
                    role: "",
                    password: ""
                }}
                validationSchema={userValidationSchema}
                onSubmit={async values => { }}
                onChange={()=> console.log("sss")}
            >
                {({
                    values,
                    setFieldValue,
                    setFieldTouched,
                    errors,
                    touched
                }) => <Form noValidate>
                        <div className="innerContainer row">
                            <div className="col-12 mb-2 ">
                                <FloatLabel label="First Name" name="firstName" value={values.firstName}>
                                    <Field
                                        type="text"
                                        className="w-100 form-control"
                                        name="firstName" />
                                    <ErrorMessage
                                        name="firstName"
                                        component="span"
                                        className="errorMessage"
                                    />
                                </FloatLabel>
                            </div>
                            <div className="col-12 mb-2">
                                <FloatLabel label="Last Name" name="lastName" value={values.lastName}>
                                    <Field
                                        type="text"
                                        className="w-100 form-control"
                                        name="lastName" />
                                    <ErrorMessage
                                        name="lastName"
                                        component="span"
                                        className="errorMessage"
                                    />
                                </FloatLabel>
                            </div>
                            <div className="col-12 mb-2">
                                <FloatLabel label="User Name" name="userName" value={values.userName}>
                                    <Field
                                        type="text"
                                        className="w-100 form-control"
                                        name="userName" />
                                    <ErrorMessage
                                        name="userName"
                                        component="span"
                                        className="errorMessage"
                                    />
                                </FloatLabel>
                            </div>
                       
                            <div className="col-12 mb-2">
                                <FloatLabel label="Password" name="password" value={values.password}>
                                    <Field
                                        type="password"
                                        className="w-100 form-control"
                                        name="password" />
                                    <ErrorMessage
                                        name="password"
                                        component="span"
                                        className="errorMessage"
                                    />
                                </FloatLabel>
                            </div>
                    </Form>
                }
            </Formik>

        </OverlayScrollbarsComponent>
        <footer>
            <Button className="button"
                disabled={!(formRef.isValid && formRef.dirty)}>
                {t("submit")}
            </Button>
        </footer>
    </div>
};

export default AddEditUser;

In this above example im using innerRef in Formik to get thier properties out of the form to disable the button but not working as expected. I tried of putting console inside innerRef I saw the value is updating

   innerRef={(ref)=> {
     console.log(ref);  // here I'm seeing the value updating whenever the form properties 
                           value changes
     formRef = ref;

   }}

but not disabling the button. Can someone help how to get properties out of formik to disable the Submit button

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

病女 2025-01-28 15:39:14

如果您阅读 https:///reactjs.s.org/docs/refocs/refs/reefs - 和the-dom.html#访问-refs 仔细。您会注意到,要利用参考,您必须使用ref.Current

SO disabled = {!(formref.isvalid&amp;&amp;&amp; formref.dirty)}&gt;应该是disabled = {! dirty)}&gt;

If you read https://reactjs.org/docs/refs-and-the-dom.html#accessing-refs carefully. You will notice that to make use of the ref, you have to use ref.current.

So disabled={!(formRef.isValid && formRef.dirty)}> should be disabled={!(formRef.current.isValid && formRef.current.dirty)}>

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文