简体   繁体   中英

Typescript problem with useFieldArray with property name

I have the following typescript problem with useFieldArray. It does not recognize at the controller under name that: 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<...>'

Then under defaultValue neither item.name nor item.value goes these subitems do not exist under item.

How can I solve this problem?

My code: https://codesandbox.io/s/stoic-frost-lpnwe?file=/src/components/BasicData.tsx

Here is the solution from the official document.

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

In the Typescript section:

for nested field array, you will have to cast the field array by its name.

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

So for your case, the name should be

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

Here is the codesandbox for demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM