【问题标题】:Typescript problem with useFieldArray with property name带有属性名称的 useFieldArray 的打字稿问题
【发布时间】:2021-07-18 09:33:59
【问题描述】:

我有以下关于 useFieldArray 的打字稿问题。它在控制器上无法识别名称为:name={test.${index}.firstname}

That's where the error comes: controller.d.ts(18, 5): The expected type comes from property 'name' which is declared here on type 'IntrinsicAttributes & { render: ({ field, fieldState, formState, }: { field: ControllerRenderProps<Record<string, any>, ${string}|${string}.${string}|${string}.${number}>; fieldState: ControllerFieldState; formState: FormState<...>; }) => ReactElement<...>; } & UseControllerProps<...>'

那么在 defaultValue 下 item.name 和 item.value 都没有这些子项在 item 下不存在。

我该如何解决这个问题?

我的代码:https://codesandbox.io/s/stoic-frost-lpnwe?file=/src/components/BasicData.tsx

【问题讨论】:

  • 我看到你的代码沙箱没有问题
  • 但是当然有问题。按名字看。当您在字符串中放置索引时,您会看到问题。 codesandbox.io/s/gifted-goldberg-tpgl6
  • 您到底想做什么?为什么这里需要一个字段数组?

标签: javascript reactjs typescript forms react-hook-form


【解决方案1】:

这是官方文档中的解决方案。

https://react-hook-form.com/api/usefieldarray/

在 Typescript 部分:

对于嵌套字段数组,您必须按字段数组的名称强制转换。

const { fields } = useFieldArray({ name: `test.${index}.keyValue` as 'test.0.keyValue' });

所以对于你的情况,名字应该是

name={`test.${index}.firstname` as `test.0.firstname`}

这里是the codesandbox for demo

【讨论】:

    猜你喜欢
    • 2019-04-20
    • 1970-01-01
    • 1970-01-01
    • 2023-01-14
    • 2021-07-25
    • 2021-08-05
    • 1970-01-01
    • 2022-07-27
    • 1970-01-01
    相关资源
    最近更新 更多