我正在尝试使用react-hook-form 的钩子创建一个动态表单useFieldArray。用户应该能够添加或删除字段,从而使其动态化。我查看了本教程以获取灵感,但缺少的部分是如何对状态实现错误验证,这将是一个对象数组:{email: string}[]。(该对象将采用更多键/值对。为了简单起见,我省略了其余部分。)
我尝试过使用yup作为验证模式。它看起来像这样:
const schema = yup.array().of(
yup.object().shape({
email: yup.string().email().required(),
}),
)
Run Code Online (Sandbox Code Playgroud)
React-hook-form 的实现是:
import * as yup from 'yup'
import { yupResolver } from '@hookform/resolvers/yup'
import { useForm, useFieldArray, Controller } from 'react-hook-form'
const { register, control, handleSubmit, errors } = useForm({
resolver: yupResolver(schema),
mode: 'onChange',
})
const { fields, append, remove } = useFieldArray({
control,
name: 'users',
})
Run Code Online (Sandbox Code Playgroud)
该表格或多或少是根据上面链接中的教程进行的。
error当控制台从钩子记录对象时useForm,它始终给出一个空对象{}。看起来好像不起作用。我可能在这里遗漏了一些东西。问题是什么?