首页 > 解决方案 > 如何让 Formik 检测 Checkbox 字段何时被选中?

问题描述

我正在制作一个需要验证的Checkbox 组件Yup(使用 完成)。但它不会从复选框中检索实际值,而只是从 inside 中检索initialValues

表格代码:

    <div className='metro custom-pg'>
      <ThemeContext.Provider theme={theme}>
        <Formik
          initialValues={{
            text: '',
            email: '',
            phone: '',
            select: '',
            multi: [],
            checkbox: false,
          }}
          validationSchema={Schema}
          onSubmit={(values) => {
            alert(JSON.stringify(values, null, 2));
            console.log("values", values);
          }}
        >
          {({
            errors,
            values,
            touched,
            handleSubmit,
            setFieldValue,
            setFieldTouched,
          }) => (
            <Form onSubmit={handleSubmit}>
              <Field
                id='text-field'
                label='Plain text'
                name='text'
                type='text'
                placeholder='Enter some characters'
                component={TextField}
              />
              <Field
                id='email-field'
                label='Email'
                name='email'
                type='email'
                placeholder='Enter your email'
                component={TextField}
              />
              <Field
                id='phone-email'
                label='Phone'
                name='phone'
                type='phone'
                placeholder='Enter your phone'
                component={TextField}
              />
              <Field
                id='select'
                name='select'
                name='select'
                label='Select an option'
                options={options}
                component={Select}
              />
              <MultiSelect
                id='multiselect'
                name='multi'
                label='Select multiple options'
                options={multiOptions}
                value={values.multi}
                onChange={setFieldValue}
                onBlur={setFieldTouched}
                touched={touched.multi}
                error={errors.multi}
              />
              <Field
                type="checkbox"
                name='check'
                id='check'
                label='Check the mark'
                component={Checkbox}
              />
              <Button variant="primary" type="submit">Submit</Button>
              </Form>
          )}
        </Formik>
      </ThemeContext.Provider>
    </div>

复选框代码:

// @flow
import * as React from "react";
import { Field, ErrorMessage } from 'formik';
import { FormGroup, FormLabel } from "react-bootstrap";

export type Props = {
  label?: String,
  id?: String,
  name?: String,
  disabled?: boolean,
  onChange: function,
  className?: string
};

export const Checkbox = ({ label, disabled, id, className }: Props) => {
  return (
    <FormGroup>
      <input type="checkbox" id={name} name={name} />
      <label htmlFor={name}> {label}</label>
      <ErrorMessage component="div" className="input-error" name="checkbox" />
    </FormGroup>
  );
};

Checkbox.defaultProps = {
  label: 'Default text',
  name: 'checkbox',
  disabled: false,
  className: ''

}

export default Checkbox;

标签: javascriptreactjsformik

解决方案


为了补充 Adrian Naranjo 的回答,您正在复选框上实现 Formik 的“onChange”回调。

<Formik
 initialValues={{ ... }}
 validationSchema={Schema}
 onSubmit={(values) => { ... }}
>
{
  ({ handleChange, ...rest } => {

您需要将其传递handleChange给您的Checkbox组件。

Formik 的Field组件将使onChange回调可用,然后您可以将其传递给<input type="checkbox" />.

https://jaredpalmer.com/formik/docs/api/field


推荐阅读