react-hook-form中的useFieldArray

WEB页面交互,表单是常见的元素,针对表单的校验/管理,react-hook-form是个常用的不错的辅助库。比如其中对于数组值的管理用到的useFieldArray,再比如嵌套复杂的组件表单用到的formContext。了解这些用法,可以更好的去使用它。

场景

在表单处理时,有时会需要处理数组表单项,比如用户可以动态添加N行的表单项。那么useFieldArray就可以面向于这种数组处理的。

例子

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
function FormTest() {
const {control, register, getValues} = useForm();
const {fields, append, prepend, remove, swap, move, insert} = useFieldArray({
control, // control props comes from useForm (optional: if you are using FormProvider)
name: "test", // unique name for your Field Array
});

console.log(fields, 'fields');
return (
<form>
{fields.map((field, index) => (
<div><input
key={field.id} // important to include key with field's id
{...register(`test.${index}.value`)}
/></div>
))}

<Button onClick={() => {
append({
value: 1,
})
}}>
Add
</Button>
{
JSON.stringify(getValues())
}
</form>
);
}

上述可以看到,当点击Button添加时,fields可以自行插入一个新值,同时每个值也一样可以走register/controller进行监听维护。

注意细节

append值必须是个对象,比如 append(1)就不行。也就是fields维护的必须是对象,比如test.${index}.value就无法设置为test.${index}

https://static.1991421.cn/2024/2024-12-06-182851.jpeg

写在最后

表单处理需求推荐尝试下该Lib解决。

相关文档