gpt4 book ai didi

javascript - 表单提交不适用于validationSchema

转载 作者:行者123 更新时间:2023-12-01 00:49:20 25 4
gpt4 key购买 nike

我想使用 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。我根据您的代码创建了一个工作示例。看看:https://stackblitz.com/edit/demo-react-formik-validation-schema

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

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

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

关于javascript - 表单提交不适用于validationSchema,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57114449/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com