如何在不提交的情况下访问 formik 字段的当前值?

How do I access current value of a formik field without submitting?

如何在我的 React 组件中访问名为 countryCodeSelectField 的值?用例是验证方案应根据国家代码更改。

  <Formik
    onSubmit={(values, actions) => this.onSubmit(values, actions.setFieldError)}
    validationSchema={() => this.registrationValidationSchema()}
    enableReinitialize={true}
    initialValues={this.props.initialData}
  >
      <Form>
          <Field
            name="countryCode"                                
            component={SelectField}
            label="Country"
            labelClassName="required"
            options={Object.entries(sortedCountryList).map(x => ({
                      value: x[1][1],
                      label: x[1][0]
                    }))}
          />
      </Form>
  </Formik>

我曾尝试通过 ref 访问它,然后通过 this.props.values(如 getFieldValue or similar in Formik 中所建议的那样),但两者 return 都未定义或为空。我的道具没有任何 "values" 字段。

编辑:找到了一个丑陋的方式:document.getElementsByName("countryCode")[0].value。更好的方法表示赞赏。

您可以像这样访问值:

<Formik
    onSubmit={(values, actions) => this.onSubmit(values, 
    actions.setFieldError)}
    validationSchema={() => this.registrationValidationSchema()}
    enableReinitialize={true}
    initialValues={this.props.initialData}
        >
          {({
            setFieldValue,
            setFieldTouched,
            values,
            errors,
            touched,
          }) => (
            <Form className="av-tooltip tooltip-label-right">
              // here you can access to values
              {this.outsideVariable = values.countryCode}
            </Form>
            )}
        </Formik>

如果你需要 formik 之外的值,你可以使用 ref

   const ref = useRef(null);
   
   const someFuncton = () => {
       console.log(ref.current.values)
   }
   
   <Formik
       innerRef={ref}
       onSubmit={(values, actions) => this.onSubmit(values,
       actions.setFieldError)}
       validationSchema={() => this.registrationValidationSchema()}
       enableReinitialize={true}
       initialValues={this.props.initialData}
   
   />
       <form></form>
   </Formik>

您可以使用 Field comp 作为包装器从 formik 获取它

import React, { ReactNode } from 'react';
import { Field, FieldProps } from 'formik';
(...other stuffs)

const CustomField = ({
  field,
  form,
  ...props
}) => {
  const currentError = form.errors[field.name];
  const currentField = field.name;  <------ THIS

  const handleChange = (value) => {
    const formattedDate = formatISODate(value);
    form.setFieldValue(field.name, formattedDate, true);
  };

  const handleError = (error: ReactNode) => {
    if (error !== currentError) {
      form.setFieldError(field.name, `${error}`);
    }
  };

  return (
      <TextField
        name={field.name}
        value={field.value}
        variant="outlined"
        helperText={currentError || 'happy helper text here'}
        error={Boolean(currentError)}
        onError={handleError}
        onChange={handleChange}
        InputLabelProps={{
          shrink: true,
        }}
        inputProps={{
          'data-testid': `${field.name}-test`, <---- very helpful for testing
        }}
        {...props}
      />
    </MuiPickersUtilsProvider>
  );
};


export default function FormikTextField({ name, ...props }) {
  return <Field variant="outlined" name={name} component={CustomField} fullWidth {...props} />;
}

非常简单,只需执行console.log(formik.values),您无需提交即可获得所有值。