使用Typescript与React和useForm。

huangapple go评论164阅读模式
英文:

Using Typescript with React and useForm

问题

以下是您要翻译的内容:

"我正在尝试将一些重复的React表单代码提取出来。我打算为从函数Field返回的输入添加一个标签,可能还有一些其他小工具。我一直在尝试为name参数使用正确的类型,但没有找到适合的类型。

以下是当前出现的错误:
类型“string”的参数不能赋给类型“'name' | 'details'”。ts(2345)
(parameter) name: string

我尝试重新定义了错误中列出的字符串联合,但它也不匹配。我说“重新发明轮子”,因为这个表单最终会有很多字段,我宁愿只列出它们一次。

以下是我的代码:

import { useForm } from 'react-hook-form';

function MyForm () {
    const { handleSubmit, register } = useForm<FormValues>();

    const onSubmit = handleSubmit((data: FormValues) => {
        console.log({data});
    });

    function Field({name}: {name: string}) {
        console.log({name})
        return (
            <>
                <input {...register(name)} />
            </>
        );
    }
    
    return (
        <form onSubmit={onSubmit}>
            <Field name={"name"} />
            <input {...register("name")} placeholder="name" />
            <input {...register("details")} placeholder="details" />
            <input type="submit" />
        </form>
    );
}

type FormValues = {
    name: string;
    details: string;
}

export default MyForm;

我尝试定义错误中列出的字符串联合,但它也不匹配。我还尝试在函数外部注册字段名称,并将其结果传递给函数。"

英文:

I am trying to factor out some repetitive code for a React form. I intend to add a label to the input returned from function Field and perhaps a few other doodads. I have been trying to use a proper type for the name parameter, but have not found one that works.

Here is the current error I get:
Argument of type 'string' is not assignable to parameter of type '"name" | "details"'.ts(2345)
(parameter) name: string

I have tried reinventing the wheel by defining the string union listed in the error, but that doesn't match either. I say "reinventing the wheel" because this form will eventually have many fields, and I'd rather list them only once.

Here is my code:

import { useForm } from &#39;react-hook-form&#39;;

function MyForm () {
    const { handleSubmit, register } = useForm&lt;FormValues&gt;();

    const onSubmit = handleSubmit ((data: FormValues) =&gt; {
        console.log({data});
    });

    function Field({name}: {name: string}) {
        console.log({name})
        return (
            &lt;&gt;
                &lt;input {...register(name)} /&gt;
            &lt;/&gt;
        );
    }
    
    return (
        &lt;form onSubmit={onSubmit}&gt;
            &lt;Field name={&quot;name&quot;} /&gt;
            &lt;input {...register(&quot;name&quot;)} placeholder=&quot;name&quot; /&gt;
            &lt;input {...register(&quot;details&quot;)} placeholder=&quot;details&quot; /&gt;
            &lt;input type=&quot;submit&quot; /&gt;
        &lt;/form&gt;
    );
}

type FormValues = {
    name: string;
    details: string;
}

export default MyForm;

I have tried defining the string union listed in the error, but that doesn't match either. I also tried registering the field name outside of the function and passing its result into the function.

答案1

得分: 1


import { useForm, FieldPath } from "react-hook-form";

function Field({ name }: { name: FieldPath<FormValues> }) {
    return <input {...register(name)} />;
}
英文:

You can utilize FieldPath generic from react-hook-form, to type the Field function.


import { useForm, FieldPath } from &quot;react-hook-form&quot;;

function Field({ name }: { name: FieldPath&lt;FormValues&gt; }) {
    return &lt;input {...register(name)} /&gt;;
}

and then this won't throw an error anymore:

&lt;Field name=&quot;name&quot; /&gt;

working example in codesandbox

huangapple
  • 本文由 发表于 2023年8月11日 04:01:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/76878967.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定