【问题标题】:Is there a better way to dynamically set Values in react-hook-form on a next.ts project?有没有更好的方法在 next.ts 项目中以 react-hook-form 动态设置值?
【发布时间】:2022-07-08 20:26:01
【问题描述】:

我正在处理一个 next.ts 项目,我需要在其中动态设置 react-hook-form 表单的字段。我发现在文字字符串中键入“name”参数的最佳方法是使用 as 运算符,如下所示:

type val = "businessName";
setValue(name as val, "Some businessName");

但我认为有一种更优雅的方法可以做到这一点,这可能会让我无法理解。 以下是关于 setValue 函数的文档:

https://react-hook-form.com/api/useform/setvalue

这是我的意思的一个基本示例,欢迎任何建议。

https://codesandbox.io/s/twilight-thunder-5ecnfu

【问题讨论】:

    标签: reactjs typescript next.js react-hook-form


    【解决方案1】:

    这实际上是更改表单值的正确方法。但是由于您使用的是打字稿,因此您可以使用类型定义来设置表单名称。

    这是一个例子。

    假设您有一个包含姓名和电子邮件的表单。但它可能是用户和电子邮件。然后你可以定义一个像下面这样的类型。

      type LoginFormValues {
        name: string,
        email: string
      } | {
        user: string,
        email: string
      }
    

    然后用 useForm 函数定义这个类型。

      const {} = useForm<LoginFormValues>()
    

    现在,您可以拥有动态表单值。

    还有其他方法可以做你想做的事,但这是最优雅的方法。 希望这会有所帮助。

    【讨论】:

    • 谢谢你的回答,它肯定很有用,但我可能解释错了。我指的是 setValue 函数的“名称”参数的类型注释。这是关于我的意思的文档:react-hook-form.com/api/useform/setvalue
    猜你喜欢
    • 2020-04-21
    • 2022-11-22
    • 2021-03-29
    • 2020-05-23
    • 2020-03-08
    • 2020-11-15
    • 2021-10-21
    • 1970-01-01
    • 2022-11-22
    相关资源
    最近更新 更多