表单提交不适用于 validationSchema

Form submission does not work with validationSchema

我想使用 Formik 和 Yup 创建动态表单。按下加号按钮时,应添加新的输入。但是,当我创建验证模式时,不会调用 onSubmit 方法。当我删除 validationSchema 时,我可以在我的控制台中看到日志。

这是我的代码:

interface Props {
    data?: string;
    onSubmit?: Function
}

interface IFormValues {
    people: {name: string, surname: string}[]
}


const FieldComponent = ({field, form: { touched, errors }}) => {
    const error = getIn(errors, field.name);
    const touch = getIn(touched, field.name);
    return (
        <div>
            <input type="text" name={field.name} onChange={field.onChange}/>
            {touch && error ? <p>{error}</p> : null}
        </div>
    )
}

const FieldArrayComponent = (arrayHelpers) => (
    <div>
        {arrayHelpers.form.values.people.map((person, index) => (
            <div key={index}>
                <Field name={`people.${index}.name`} component={FieldComponent}/>
                <Field name={`people.${index}.surname`} component={FieldComponent}/>
                <button type="button" onClick={() => arrayHelpers.push({name: '', surname: ''})}>+</button>
                <button type="button" onClick={() => arrayHelpers.remove(index)}>-</button>
            </div>
        ))}
    <div>
        <button type="submit">Submit</button>
    </div>
</div>
)

export const FormComponent: React.FunctionComponent<Props> = (props) => {
    const initialValues: IFormValues = {
        people: [{name: '', surname: ''}]
    }
    const schema = yup.object().shape({
        people: yup.array().of(
            yup.object().shape({
                name: yup.string().required('Required'),
                surname: yup.string().required('Required')
            })
        )
    })
    return (
        <Formik
        initialValues={initialValues}
        onSubmit={values => {
            console.log(values);
        }}
        validationSchema={schema}
        render={({ values }) => (
          <Form>
            <FieldArray
                name="people"
                component={FieldArrayComponent}
            />
          </Form>
        )}
      />
    )
}

你能看看我做错了什么吗?

传递validationSchema的目的是确保onSubmit不会在有errors的情况下被调用。我根据您的代码创建了一个工作示例。看看:https://stackblitz.com/edit/demo-react-formik-validation-schema

您可以看到如果没有错误,onSubmit 确实会被调用。但如果必填字段为空,则不会调用 onSubmit。这是预期的行为。

但是,如果您的目的是在出现错误的情况下进行调试(这是我经常需要做的事情),请查看 Formikrender 方法,您可以在其中 console.log(values, errors) 查看表单错误或值而不是登录 onSubmit.

render = {({ values, errors }) => {
  console.log(values, errors);
  return <Form>
    <FieldArray
      name="people"
      component={FieldArrayComponent}
    />
  </Form>
}}