reactjs 使用react-hook-form的register函数时发生TypeScript错误

dddzy1tm  于 2023-05-06  发布在  React
关注(0)|答案(1)|浏览(185)

我试图使用react-hook-form及其useFieldArray钩子注册数组元素,我得到了这个TypeScript错误:Argument of type 'phases.${number}.name' is not assignable to parameter of type '"_id" | "name" | "description" | "phases" | "isPrivate" | "createdBy" | "phases.0" | "phases.0.name" | "phases.0.description" | "phases.0.order"'.基本上它不能regconize,因为索引可以是不同于0的东西。
代码如下:

interface IPhaseTemplate {
  _id: string;
  name: string;
  description: string;
  phases: [
    {
      name: string;
      description: string;
      order: number;
    }
  ];
  isPrivate: boolean;
  createdBy: string;
}
function CreateNew({ updateStep }: CreatePhaseTemplateProps) {
  const {
    register,
    handleSubmit,
    formState: { errors },
    control,
  } = useForm<IPhaseTemplate>({
    defaultValues: data ?? {
      name: "",
      description: "",
      isPrivate: false,
      phases: [
        {
          name: "",
          description: "",
          order: 0,
        },
      ],
    },
  });
  const { fields, append, remove } = useFieldArray({
    control,
    name: "phases",
  });
  return (
    <Box component="form" onSubmit={handleSubmit(onSubmit)}>
      <Stack spacing={1} alignItems="center">
        {fields.map((field, index) => (
          <Card sx={{ m: 1 }} key={field.id}>
            <CardContent>
              <TextField
                label="Name"
                fullWidth
                {...register(`phases.${index}.name` as const, {
                  required: "Name is required",
                })}
                error={!!errors.phases?.[index]?.name}
                helperText={errors.phases?.[index]?.name?.message}
                sx={{ mb: 1 }}
              />
              <TextField
                label="Description"
                fullWidth
                multiline
                rows={4}
                {...register(`phases.${index}.description` as const, {
                  required: "Description is required",
                })}
                error={!!errors.phases?.[index]?.description}
                helperText={errors.phases?.[index]?.description?.message}
              />
            </CardContent>
            <CardActions>
              <Button size="small" onClick={() => remove(index)}>
                Remove
              </Button>
            </CardActions>
          </Card>
        ))}
      </Stack>
    </Box>
  );
}

错误出现在phases.${index}.name as const部分和描述部分。 我试过在https://react-hook-form.com/api/usefieldarray/#main上使用钩子并使用as const`输入register部分,但TypeScript仍然对我大喊大叫

jdgnovmf

jdgnovmf1#

尝试定义您的界面如下:

interface IPhaseTemplate {
  _id: string;
  name: string;
  description: string;
  phases:{
      name: string;
      description: string;
      order: number;
    }[];
  isPrivate: boolean;
  createdBy: string;
}

相关问题