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

React Hook Form提交字符串数组失败问题求助

React Hook Form 提交字符串数组解决方案

不需要嵌套表单,核心是让字符串数组成为React Hook Form的表单状态一部分,官方推荐用useFieldArray来管理动态数组,这样提交时数组会自动包含在表单数据里,同时能实现实时UI更新。

父组件(主表单)

import { useForm, useFieldArray } from 'react-hook-form';
import { Box, Button, FormControl, FormLabel, Input } from '@chakra-ui/react';
import CreateMessage from './CreateMessage';

export default function ParentForm() {
  const { register, handleSubmit, control } = useForm({
    defaultValues: {
      title: '', // 其他表单字段示例
      messages: [] // 初始化消息数组
    }
  });

  // 用useFieldArray管理messages数组,自动同步表单状态
  const { fields, append, remove } = useFieldArray({
    control,
    name: 'messages' // 对应表单字段名,必须和defaultValues里的key一致
  });

  const onSubmit = (data) => {
    // 此时data会包含title和messages数组,直接提交到后端即可
    console.log('提交数据:', data);
    // fetch('/api/submit', { method: 'POST', body: JSON.stringify(data) })
  };

  return (
    <Box p={4} maxW="md" mx="auto">
      <form onSubmit={handleSubmit(onSubmit)}>
        {/* 其他表单字段 */}
        <FormControl mb={4}>
          <FormLabel>标题</FormLabel>
          <Input {...register('title', { required: true })} />
        </FormControl>

        {/* 传递数组操作方法给子组件 */}
        <CreateMessage 
          fields={fields} 
          addMessage={(text) => append({ value: text })} 
          deleteMessage={remove}
        />

        <Button type="submit" colorScheme="blue" mt={4}>提交</Button>
      </form>
    </Box>
  );
}

子组件(CreateMessage)

import { useState } from 'react';
import { Box, Input, Button, HStack, Text } from '@chakra-ui/react';

export default function CreateMessage({ fields, addMessage, deleteMessage }) {
  const [inputText, setInputText] = useState('');

  const handleAdd = () => {
    if (inputText.trim()) {
      addMessage(inputText.trim());
      setInputText('');
    }
  };

  const handleEnterKey = (e) => {
    if (e.key === 'Enter') {
      e.preventDefault();
      handleAdd();
    }
  };

  return (
    <Box mb={4}>
      <HStack mb={2}>
        <Input
          placeholder="输入消息内容"
          value={inputText}
          onChange={(e) => setInputText(e.target.value)}
          onKeyDown={handleEnterKey}
        />
        <Button onClick={handleAdd} colorScheme="green">添加</Button>
      </HStack>

      {/* 实时展示已添加的消息 */}
      <Box mt={2}>
        {fields.map((item, index) => (
          <HStack key={item.id} justify="space-between" p={2} bg="gray.50" borderRadius="md">
            <Text>{item.value}</Text>
            <Button size="sm" colorScheme="red" onClick={() => deleteMessage(index)}>删除</Button>
          </HStack>
        ))}
      </Box>
    </Box>
  );
}

关键说明

  1. useFieldArray 作用:自动将数组与表单状态绑定,调用append/remove时会同步更新表单的messages字段,提交时自然被包含。
  2. 避免独立维护状态:不要在子组件自己维护数组状态,否则无法同步到React Hook Form的表单数据里。
  3. 表单上下文:子组件必须在父组件的<form>标签内,或者通过FormProvider传递上下文(如果组件层级深),确保操作能同步到主表单。

内容的提问来源于stack exchange,提问作者Mario Garcia Pinan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 20:42:37