簡體   English   中英

啟用和禁用帶有復選框的提交按鈕

[英]Enabling and disabling submit button with checkboxes

我正在為我的 React forms 使用 Formik,我也很新,我有一個帶有兩個復選框和一個默認禁用的提交按鈕的表單。 我需要找到一種方法來檢查復選框是否已被選中。 如果已選中所有兩個復選框,則啟用提交按鈕,如果未選中任何復選框,則提交按鈕保持禁用狀態。

我的代碼:

FormikWithRef:

import React, { useEffect, forwardRef, useImperativeHandle } from 'react';
import { Formik } from 'formik';

function FormikWithRef(props, ref) {
  let formikPropObj = {};

  useImperativeHandle(ref, () => formikPropObj);
  useEffect(() => {
    if (props.refSetter && props.invokable)
      props.refSetter({
        ref: ref.current,
        invokableFunction: props.invokable,
      });
  }, []);

  return (
    <Formik {...props}>
      {(formikProps) => {
        formikPropObj = formikProps;
        if (typeof props.children === 'function') {
          return props.children(formikProps);
        }
        return props.children;
      }}
    </Formik>
  );
}

export default forwardRef(FormikWithRef);

注冊表格:

import React from 'react';
import PropTypes from 'prop-types';
import FormikWithRef from './FormikWithRef';

const RegisterForm = ({
  formRef,
  internalRef,
  children,
  initialValues,
  validationSchema,
  onSubmit,
  enableReinitialize,
  validateOnMount,
  initialTouched,
  invokable,
  refSetter,
}) => {
  return (
    <FormikWithRef
      enableReinitialize={enableReinitialize}
      validateOnMount={validateOnMount}
      initialTouched={initialTouched}
      validateOnChange
      validateOnBlur
      initialValues={initialValues}
      validationSchema={validationSchema}
      onSubmit={onSubmit}
      ref={formRef}
      internalRef={internalRef}
      invokable={invokable}
      refSetter={refSetter}
    >
      {(props) => (
        <form ref={internalRef} onSubmit={props.handleSubmit}>
          {children}
        </form>
      )}
    </FormikWithRef>
  );
};

RegisterForm.propTypes = {
  formRef: PropTypes.object,
  children: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.node), PropTypes.node]),
  initialValues: PropTypes.object,
  validationSchema: PropTypes.oneOfType([PropTypes.object, PropTypes.func]),
  onSubmit: PropTypes.func,
  enableReinitialize: PropTypes.bool,
  validateOnMount: PropTypes.bool,
  initialTouched: PropTypes.object,
  internalRef: PropTypes.func,
  handleSubmit: PropTypes.func,
  invokable: PropTypes.func,
  refSetter: PropTypes.func,
};

RegisterForm.defaultProps = {
  formRef: null,
  children: null,
  initialValues: {},
  validationSchema: null,
  onSubmit: () => {},
  enableReinitialize: false,
  validateOnMount: false,
  initialTouched: {},
  internalRef: null,
  handleSubmit: null,
  invokable: null,
  refSetter: null,
};

export default RegisterForm;

注冊組件:

import React, { useState, useRef } from 'react';
import Registerform from './RegisterForm';
import useUserApi from './useUserApi'; 

  const RegisterForm = () => {
         const [submitting, setSubmitting] = useState(false);
         const [isSubmitted, setIsSubmitted] = useState(false);
         const [disableSubmit, setDisableSubmit] = useState(true);
         const formRef = useRef();

        const initialValues = {
             cookies: false,
             terms: false,
         };

       const {register} = useUserApi();

        const submitRegisterForm = async (values) => {
          const body = {
                terms: values?.terms || null,
                cookies: values?.cookies || null,
           };

            const res = await register(body);

           return res;
        };

  const onFormSubmit = async (values, { setErrors }) => {
    setSubmitting(true);
    const result = await submitRegisterForm(values);

    if (result && !(await checkErrors(result))) {
      setSubmitting(false);
      setIsSubmitted(true);
      return true;
    }
    if (result.status === 500)
      setErrors('A problem occurred submitting form.');

    setIsSubmitted(false);
    setSubmitting(false);
    return false;
  };

 useEffect(() => {
    if (isSubmitted) {
      const historyScreen = reverse(`${routes.users}`);
      history.push(historyScreen);
    }
  }, [isSubmitted]);


     return initialValues ? (
        <FormWrapper>
          <RegisterForm
            initialValues={initialValues}
            onSubmit={onFormSubmit}
            formRef={formRef}
          >
           
            <InputWrapper width="50%" verticalAlign="top">
              <CheckBox
                label={
                  <LabelText>I have agreed to terms</LabelText>
                }
                name="terms"
                id="terms"
              />
            </InputWrapper>
            <InputWrapper width="50%" verticalAlign="top">
              <CheckBox
                label={
                  <LabelText>I agree to cookies.</LabelText>
                }
                name="cookies"
                id="cookies"
              />
            </InputWrapper>
           
            <ButtonWrapper>
            
              <SaveButton
                type="submit"
                buttonText="Register"
                disabled={disableSubmit}
              />
            </ButtonWrapper>
          </Form>
        </FormWrapper>
      ) : null;

 }
export default RegisterForm;

您需要公開 RegisterForm 中的值。 我認為props也應該具有values 所以改變你的代碼如下

 <FormikWithRef
      enableReinitialize={enableReinitialize}
      validateOnMount={validateOnMount}
      initialTouched={initialTouched}
      validateOnChange
      validateOnBlur
      initialValues={initialValues}
      validationSchema={validationSchema}
      onSubmit={onSubmit}
      ref={formRef}
      internalRef={internalRef}
      invokable={invokable}
      refSetter={refSetter}
    >
      {(props) => (
        <form ref={internalRef} onSubmit={props.handleSubmit}>
          {children(props.values)} // make your children as a function
        </form>
      )}
    </FormikWithRef>

現在,當您渲染RegisterForm時,您可以執行此操作

<RegisterForm
  initialValues={initialValues}
  onSubmit={onFormSubmit}
  formRef={formRef}
>
  {(values) => { // consume the value here 
    return (
      .....
      <ButtonWrapper>
      <SaveButton type="submit" buttonText="Register" disabled={!(values.terms && values.cookies)} />
    </ButtonWrapper>
    )
  }}
</RegisterForm>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM