如何在React Hook Form中管理widthOptions字符串数组(无需普通状态)
使用React Hook Form实现动态宽度选项数组(无需自定义状态)
核心思路
React Hook Form内置了对数组字段的原生支持,无需额外维护useState,直接通过register、getValues和setValue这几个API就能完成数组的增删改操作。
完整实现代码
import { TrashIcon } from "@heroicons/react/24/outline"; import { useForm } from "react-hook-form"; // 定义表单类型,保证类型安全 type MaterialForm = { widthOptions: string[]; tempWidth: string; // 临时存储新增宽度的输入值 }; const Test = () => { const { register, getValues, setValue, watch } = useForm<MaterialForm>({ defaultValues: { widthOptions: [], tempWidth: "" } }); // 实时监听widthOptions数组的变化,用于渲染列表 const widthOptions = watch("widthOptions"); // 添加宽度选项 const addWidthOption = () => { const tempValue = getValues("tempWidth").trim(); if (!tempValue) return; // 空值不添加 const currentOptions = getValues("widthOptions"); // 更新数组,同时清空临时输入框 setValue("widthOptions", [...currentOptions, tempValue]); setValue("tempWidth", ""); }; // 删除指定索引的宽度选项 const removeWidthOption = (index: number) => { const currentOptions = getValues("widthOptions"); setValue("widthOptions", currentOptions.filter((_, i) => i !== index)); }; return ( <div> {/* 新增选项的输入框 */} <input type="text" {...register("tempWidth")} placeholder="输入宽度值" /> <button onClick={addWidthOption}>添加宽度选项</button> {/* 渲染已添加的选项列表 */} {widthOptions.map((option, index) => ( <div key={index} className="flex gap-2 mt-2"> {/* 通过数组索引绑定输入框,自动同步到表单状态 */} <input type="text" {...register(`widthOptions.${index}` as const)} /> <button type="button" onClick={() => removeWidthOption(index)} aria-label="删除选项" > <TrashIcon className="w-5 h-5 text-gray-500" /> </button> </div> ))} </div> ); }; export default Test;
关键细节说明
- 数组字段绑定:通过
register(widthOptions.${index})的语法,直接将输入框与数组中对应索引的元素绑定,无需手动编写onChange逻辑,React Hook Form会自动同步输入值到表单状态。 - 数组操作逻辑:
- 添加:用
getValues获取当前数组和临时输入值,通过setValue更新数组并清空临时输入框。 - 删除:过滤掉指定索引的元素后,用
setValue更新数组。
- 添加:用
- 类型安全:通过TypeScript定义表单类型
MaterialForm,避免字段类型错误,提升开发体验。
内容的提问来源于stack exchange,提问作者Bowis
相关产品推荐
相关产品推荐

