You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用react-hook-form的useFieldArray独立处理两个数组表单字段?

React Hook Form 多数组字段独立管理方案

解决这个问题的核心是:给每个数组字段单独调用一次useFieldArray,并为返回的变量设置不同的别名,不能共用同一组fields/append/remove,也不能在同一个useFieldArray配置里传多个name属性(对象重复键会被覆盖,所以之前的写法无效)。

完整实现代码

1. 初始化表单与数组控制器

import { useForm, useFieldArray } from "react-hook-form";

const MyForm = () => {
  const {
    register,
    handleSubmit,
    formState: { errors },
    control,
  } = useForm({
    // 可选:设置数组默认空值,确保初始结构正确
    defaultValues: {
      habilidades: [],
      aptitudes: []
    }
  });

  // 单独管理habilidades数组,给返回值起别名避免冲突
  const { 
    fields: habilidadesFields, 
    append: appendHabilidad, 
    remove: removeHabilidad 
  } = useFieldArray({
    control,
    name: "habilidades",
  });

  // 单独管理aptitudes数组,同样设置独立别名
  const { 
    fields: aptitudesFields, 
    append: appendAptitud, 
    remove: removeAptitud 
  } = useFieldArray({
    control,
    name: "aptitudes",
  });

  // 提交处理函数
  const onSubmit = (data) => {
    console.log(data); // 输出结构符合预期
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      {/* 表单字段部分 */}
      {/* ... */}
    </form>
  );
};

export default MyForm;

2. 表单字段渲染

将两个数组的渲染逻辑分开,各自使用对应的fields、append和remove方法:

<div>
  <label>Habilidades</label>
  {habilidadesFields.map((item, index) => (
    <div key={item.id}>
      <input
        {...register(`habilidades.${index}`, { required: true })}
        placeholder="Ingresa una habilidad"
      />
      {/* 调用专属的remove方法 */}
      <button type="button" onClick={() => removeHabilidad(index)}>
        Eliminar
      </button>
    </div>
  ))}
  {/* 调用专属的append方法 */}
  <button
    type="button"
    onClick={() => appendHabilidad("")}
  >
    Nueva habilidad
  </button>
</div>

<div>
  <label>Aptitudes</label>
  {aptitudesFields.map((item, index) => (
    <div key={item.id}>
      <input
        {...register(`aptitudes.${index}`, { required: true })}
        placeholder="Ingresa una aptitud"
      />
      <button type="button" onClick={() => removeAptitud(index)}>
        Eliminar
      </button>
    </div>
  ))}
  <button
    type="button"
    onClick={() => appendAptitud("")}
  >
    Nueva aptitud
  </button>
</div>

{/* 提交按钮 */}
<button type="submit">Enviar formulario</button>

最终效果

提交表单后,得到的数据结构完全符合预期:

{
  "habilidades": ["example1", "example2", "example3"],
  "aptitudes": ["example4", "example5", "example6"]
}

内容的提问来源于stack exchange,提问作者Romera02

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 07:25:25