表单提交不适用于validationSchema

时间:2019-07-19 14:21:18

标签: javascript reactjs forms formik

我想使用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>
        )}
      />
    )
}

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

1 个答案:

答案 0 :(得分:1)

传递validationSchema的目的是确保如果有onSubmit时不会调用errors。我根据您的代码创建了一个有效的示例。看看:https://stackblitz.com/edit/demo-react-formik-validation-schema

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

但是,如果您打算在存在错误的情况下进行调试(这是我经常要做的事情),请检出render的{​​{1}}方法,您可以在其中{{1 }}来查看表单错误或值,而不是登录Formik

console.log(values, errors)