React Hook Form的useFieldArray无法显示数据
P粉176151589
P粉176151589 2023-09-01 23:30:48
[React讨论组]

大家好,我使用React Hook Form和useFieldArray Hook创建了一个Material UI表单。

<Box component="form" onSubmit={handleSubmit(submit)}>
      <Grid container spacing={2}>
        <Grid item xs={12} sm={12} md={12} lg={12}>
          <TextField
            label="Evnet Name"
            fullWidth
            {...register("eventName")}
            name="eventName"
          />
        </Grid>

        <Grid item xs={12} sm={12} md={6} lg={6} alignSelf="center">
          <TextField
            label="Evnet Venue Name"
            fullWidth
            {...register("eventVenue")}
            name="eventVenue"
          />
        </Grid>
         <Box sx={{ width: "100%" }}>
          <DialogTitle
            sx={{ fontWeight: "bold", textTransform: "uppercase" }}
          >
            Ticket Category
          </DialogTitle>
        </Box>
        <Grid item xs={12} sm={12} md={5} lg={4}>
          <TextField
            label="Category"
            fullWidth
            {...register("ticketCatName")}
            name="ticketCatName"
          />
        </Grid>

        <Grid item xs={12} sm={12} md={3} lg={3}>
          <TextField
            type="number"
            label="Price"
            fullWidth
            {...register("ticketCatPrice")}
            name="ticketCatPrice"
          />
        </Grid>

        <Grid item xs={12} sm={12} md={3} lg={3}>
          <TextField
            type="number"
            label="Total"
            fullWidth
            {...register("ticketCatTotal")}
            name="ticketCatTotal"
          />
        </Grid>
This Values I am getting when I submit the form. 
</Box>

我创建了一个动态表单组件,使用map来显示。

{fields.map((item, index) => {
              return (
                <MoreFields
                  register={register}
                  key={item.id}
                  remove={remove}
                  index={index}
                  item={item}
                  control={control}
                />
              );
            })}

当我提交表单时,fields数组中的值不显示数据,而fields数组之外的其他字段正常工作。

这是组件的代码。

import { Box, Grid, IconButton, SvgIcon, TextField } from "@mui/material";
import React from "react";
import DeleteIcon from '@mui/icons-material/Delete';
import { Fragment } from "react";

const MoreFields = ({ register, remove, index, item }) => {
  return (
    <Fragment key={item.id}>
      <Grid item xs={12} sm={12} md={5} lg={4}>
        <TextField
          label="Category"
          fullWidth
          {...register(`ticketCategory.${index}.ticketCatName`)}
          name={`ticketCategory${index}.ticketCatName`}
          defaultValue={item.ticketCatName}
        />
      </Grid>

      <Grid item xs={12} sm={12} md={3} lg={3}>
        <TextField
          type="number"
          label="Price"
          fullWidth
          {...register(`ticketCategory.${index}.ticketCatPrice`)}
          name={`ticketCategory${index}.ticketCatPrice`}
          defaultValue={item.ticketCatPrice}
        />
      </Grid>

      <Grid item xs={12} sm={12} md={3} lg={3}>
        <TextField
          type="number"
          label="Total"
          fullWidth
          {...register(`ticketCategory.${index}.ticketCatTotal`)}
          name={`ticketCategory${index}.ticketCatTotal`}
          defaultValue={item.ticketCatTotal}
         
        />
      </Grid>

      <Grid item xs={4} sm={4} md={2} lg={2} alignSelf="center">
        <SvgIcon color='error' onClick={()=>remove(index)} sx={{cursor:'pointer'}}>
          <DeleteIcon size="medium" />
        </SvgIcon>
      </Grid>
      </Fragment>
  );
};

export default MoreFields;

我可以添加和删除字段,但是当提交时,值不会显示。不知道为什么,请帮帮我。

我正在使用的hooks和函数。

const { register, handleSubmit, control } = useForm();
  const { fields, append, prepend, remove, swap, move, insert } = useFieldArray(
    {
      control,
      name: "ticketCategory",
    }
  );
  const addFields = () => {
    append({ ticketCatName: "", ticketCatPrice: "", ticketCatTotal: "" });
  };

  const submit = (data) => {
    console.log(data);
  };

P粉176151589
P粉176151589

全部回复(1)
P粉250422045

你应该像这样同时使用相同的名称来注册和命名属性:

<TextField
  label="Category"
  fullWidth
  {...register(`ticketCategory.${index}.ticketCatName`)}
  name={`ticketCategory.${index}.ticketCatName`}
  defaultValue={item.ticketCatName}
/>;

React Hook Form需要你在数组名称中添加索引,因为它使用点表示法来访问嵌套字段。例如,假设你有一个像这样的对象数组:

{
  "ticketCategory": [
    {
      "ticketCatName": "A",
      "ticketCatPrice": 10,
      "ticketCatTotal": 100
    },
    {
      "ticketCatName": "B",
      "ticketCatPrice": 20,
      "ticketCatTotal": 200
    }
  ]
}

然后,每个输入的名称应该与表单数据中字段的路径相匹配。例如,第一个票类别名称输入应该具有名称ticketCategory.0.ticketCatName,第二个票类别价格输入应该具有名称ticketCategory.1.ticketCatPrice。这样,React Hook Form可以控制输入值到表单数据中。

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号