,可以通过以下步骤解决:
import { useForm } from 'react-hook-form';
const MyForm = () => {
const { register, handleSubmit, control } = useForm({
defaultValues: {
fields: [{ name: '' }],
},
});
// 其他代码...
}
import { useFieldArray } from 'react-hook-form';
const MyForm = () => {
const { register, handleSubmit, control } = useForm({
defaultValues: {
fields: [{ name: '' }],
},
});
const { fields, append, remove } = useFieldArray({
control,
name: 'fields',
});
// 其他代码...
}
import { useFieldArray, Controller } from 'react-hook-form';
const MyForm = () => {
const { register, handleSubmit, control } = useForm({
defaultValues: {
fields: [{ name: '' }],
},
});
const { fields, append, remove } = useFieldArray({
control,
name: 'fields',
});
return (
<form onSubmit={handleSubmit(onSubmit)}>
{fields.map((field, index) => (
<div key={field.id}>
<Controller
control={control}
name={`fields[${index}].name`}
defaultValue={field.name}
render={({ field }) => (
<input {...field} />
)}
/>
<button type="button" onClick={() => remove(index)}>
删除
</button>
</div>
))}
<button type="button" onClick={() => append({ name: '' })}>
添加字段
</button>
<input type="submit" value="提交" />
</form>
);
}
import { useFieldArray, Controller } from 'react-hook-form';
const MyForm = () => {
const { register, handleSubmit, control } = useForm({
defaultValues: {
fields: [{ name: '' }],
},
});
const { fields, append, remove } = useFieldArray({
control,
name: 'fields',
});
const onSubmit = (data) => {
console.log(data);
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
{/* 表单字段渲染代码 */}
</form>
);
}
以上是在React Hook窗体中使用useFieldArray时动态添加错误的解决方案。通过使用React Hook Form提供的useFieldArray钩子函数,我们可以轻松地处理动态字段数组,并实现表单的动态添加和删除功能。这种方法简化了表单的处理过程,并提供了更好的用户体验。
推荐的腾讯云相关产品:腾讯云云服务器(CVM)和腾讯云云数据库MySQL。
领取专属 10元无门槛券
手把手带您无忧上云