如何禁用与Formik集成的MUI提交按钮?

发布于 2025-01-22 09:36:50 字数 2800 浏览 5 评论 0原文

我正在尝试将Formik与MUI集成以具有按钮组件,如下所示:

import React from "react";
import { Button } from "@mui/material";
import { useFormikContext } from "formik"; 

const ButtonWrapper = ({ children, ...otherProps }) => {
    const { submitForm } = useFormikContext();

    const handleSubmit = () => {
        submitForm();
    };

    const configButton = {
        ...otherProps,
        variant: "contained",
        color: "primary",
        fullWidth: true,
        onClick: handleSubmit,
    };

    return <Button {...configButton}>{children}</Button>;
};

export default ButtonWrapper;

这是我使用上述代码段,但我想知道如何在这两种情况下禁用提交按钮:1:1根据形式的有效性,2。

<Grid item xs={12}>              
  <ButtonWrapper>Submit</ButtonWrapper>
</Grid>

我一直在寻找我应该使用Isvalid,Issubmitting&amp;肮脏的属性,但我想知道如何将其实现到首先显示的代码中。

如果有帮助,这是表单验证的一部分。

const INITIAL_FORM_STATE = {
    name: "",
    role: "",
};
const FORM_VALIDATION = Yup.object().shape({
    name: Yup.string().required("Required").min(2, "Enter full name"),
    role: Yup.string().required("Required"),
});

const AddUsersAdmin = () => {
    return (
        <Grid container>
            <Grid item xs={12}>
                <Container maxWidth="md">
                    <div>
                        <Formik
                            initialValues={{
                                ...INITIAL_FORM_STATE,
                            }}
                            validationSchema={FORM_VALIDATION}
                            onSubmit={(values) => {
                                console.log(values);
                                console.log(values["role"]);
                            }}
                        >
                            <Form>
                                <Grid container spacing={2}>
                                    <Grid item xs={6}>
                                        <TextfieldWrapper name="name" label="Name" />
                                    </Grid>
                                    <Grid item xs={6}>
                                        <SelectWrapper name="role" label="Role" options={role} />
                                    </Grid>
                                    <Grid item xs={12}>
                                        <ButtonWrapper disabled>Submit</ButtonWrapper>
                                    </Grid>
                                </Grid>
                            </Form>
                        </Formik>
                    </div>
                </Container>
            </Grid>
        </Grid>

    );
};

I'm trying to integrate Formik with Mui in order to have a button component, as follow:

import React from "react";
import { Button } from "@mui/material";
import { useFormikContext } from "formik"; 

const ButtonWrapper = ({ children, ...otherProps }) => {
    const { submitForm } = useFormikContext();

    const handleSubmit = () => {
        submitForm();
    };

    const configButton = {
        ...otherProps,
        variant: "contained",
        color: "primary",
        fullWidth: true,
        onClick: handleSubmit,
    };

    return <Button {...configButton}>{children}</Button>;
};

export default ButtonWrapper;

This is the code snippet in which I used the above, but I wonder how could I disable the submit button in each of this two cases: 1. according to the validity of the form state, 2. when the form submittion is in progress.

<Grid item xs={12}>              
  <ButtonWrapper>Submit</ButtonWrapper>
</Grid>

I was looking that I should use isValid, isSubmitting & dirty properties but I wonder how can I implement those into the code shown first.

If this helps, this is part of the form validation.

const INITIAL_FORM_STATE = {
    name: "",
    role: "",
};
const FORM_VALIDATION = Yup.object().shape({
    name: Yup.string().required("Required").min(2, "Enter full name"),
    role: Yup.string().required("Required"),
});

const AddUsersAdmin = () => {
    return (
        <Grid container>
            <Grid item xs={12}>
                <Container maxWidth="md">
                    <div>
                        <Formik
                            initialValues={{
                                ...INITIAL_FORM_STATE,
                            }}
                            validationSchema={FORM_VALIDATION}
                            onSubmit={(values) => {
                                console.log(values);
                                console.log(values["role"]);
                            }}
                        >
                            <Form>
                                <Grid container spacing={2}>
                                    <Grid item xs={6}>
                                        <TextfieldWrapper name="name" label="Name" />
                                    </Grid>
                                    <Grid item xs={6}>
                                        <SelectWrapper name="role" label="Role" options={role} />
                                    </Grid>
                                    <Grid item xs={12}>
                                        <ButtonWrapper disabled>Submit</ButtonWrapper>
                                    </Grid>
                                </Grid>
                            </Form>
                        </Formik>
                    </div>
                </Container>
            </Grid>
        </Grid>

    );
};

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

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

发布评论

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

评论(1

久光 2025-01-29 09:36:51

这是一个示例,如何通过无效的形式传递残疾人道具。

import React from 'react';
import { Formik, Form, Field } from 'formik';
import * as Yup from 'yup';

const SignupSchema = Yup.object().shape({
  firstName: Yup.string()
    .min(2, 'Too Short!')
    .max(50, 'Too Long!')
    .required('Required'),
  });

export const ValidationSchemaExample = () => (
  <div>
    <h1>Signup</h1>
    <Formik
      initialValues={{
        firstName: '',
      }}
      validationSchema={SignupSchema}
      onSubmit={values => {
        // same shape as initial values
        console.log(values);
      }}
    >
      {({ errors, touched }) => (
        <Form>
          <Field name="firstName" />
            <ButtonWrapper disabled={erros.length>0}>Submit</ButtonWrapper>
        </Form>
      )}
    </Formik>
  </div>
);

正如您之前提到的那样,如果您要在提交表单时也要禁用它,请考虑如何通过Isfetching或Isloading(例如iSfetching或isloading),以便您可以使用类似的东西:

<ButtonWrapper disabled={erros.length>0 || isLoading}>Submit</ButtonWrapper>

如果您使用MUI组件,则可以将其集成在一起通过将一些formik道具传递给MUI组件。

示例:

 <TextField
          fullWidth
          id="firstName"
          name="firstName"
          label="firstName"
          value={formik.values.firstName}
          onChange={formik.handleChange}
          error={formik.touched.firstName && Boolean(formik.errors.firstName)}
        />

有关更多详细信息:
https://formik.org/docs/examples/examples/examples/examples/with-material-with-material-paterial-ui

Here is an example how you can pass the disabled props in case of invalidated form.

import React from 'react';
import { Formik, Form, Field } from 'formik';
import * as Yup from 'yup';

const SignupSchema = Yup.object().shape({
  firstName: Yup.string()
    .min(2, 'Too Short!')
    .max(50, 'Too Long!')
    .required('Required'),
  });

export const ValidationSchemaExample = () => (
  <div>
    <h1>Signup</h1>
    <Formik
      initialValues={{
        firstName: '',
      }}
      validationSchema={SignupSchema}
      onSubmit={values => {
        // same shape as initial values
        console.log(values);
      }}
    >
      {({ errors, touched }) => (
        <Form>
          <Field name="firstName" />
            <ButtonWrapper disabled={erros.length>0}>Submit</ButtonWrapper>
        </Form>
      )}
    </Formik>
  </div>
);

And as you mentioned before that in case you want to disabled it also when submiting the form , think about how to pass another props like isFetching or isLoading so you could have something like :

<ButtonWrapper disabled={erros.length>0 || isLoading}>Submit</ButtonWrapper>

In case you are using mui components, you can integrate it with formik by pass some formik props to mui components.

Example:

 <TextField
          fullWidth
          id="firstName"
          name="firstName"
          label="firstName"
          value={formik.values.firstName}
          onChange={formik.handleChange}
          error={formik.touched.firstName && Boolean(formik.errors.firstName)}
        />

For more details:
https://formik.org/docs/examples/with-material-ui

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