【问题标题】:How to set a numeric value in defaultValues for react-hook-form in order to be required?如何在默认值中为 react-hook-form 设置一个数值以便需要?
【发布时间】:2022-01-13 12:43:59
【问题描述】:

有一个表单包含两个输入,一个字符串和一个数字都是必需的。

这是架构:

const schema = yup.object().shape({
  name: yup.string().required(),
  age: yup.number().required()
});

之后就是react-hook-form:

  const { handleSubmit, reset, control, register, watch } = useForm({
    defaultValues: emptyObject,
    resolver: yupResolver(schema)
  });

如您所见,defaultValuesemptyObject

这里是:

const emptyObject = {
  name: '',
  age: 0
}

name 部分工作正常,如果该文本框中没有写入任何输入,我无法提交数据,但对于年龄而言,它不需要任何值。我知道它会检查值并发现它是 0 并且它认为有输入。

但是如何改变它以使其工作?尝试使用null,但仍然无法正常工作。

不得不提的是,它是 React with Typescript,所以当年龄设置为 null 时,还有一个界面会抛出错误。

  MyData: {
    name: string;
    age: number;
  }

【问题讨论】:

  • 不能删除默认值吗?你为什么需要一个?你可以放置一个占位符而不是默认值

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


【解决方案1】:

我从https://react-hook-form.com/get-started#Applyvalidation得到这个

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

interface IFormInput {
  firstName: string;
  lastName: string;
  age: number;
}

export default function App() {
  const { register, handleSubmit } = useForm<IFormInput>();
  const onSubmit: SubmitHandler<IFormInput> = data => console.log(data);
   
  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input {...register("firstName", { required: true, maxLength: 20, placeHolder: "John" })} />
      <input {...register("lastName", { pattern: /^[A-Za-z]+$/i })} />
      <input type="number" {...register("age", { min: 18, max: 99 })} />
      <input type="submit" />
    </form>
  );
}

这可以作为一个例子吗?

【讨论】:

    【解决方案2】:

    也将age 设为空string,这只是为了满足您的需要,并且在提交表单时只需添加一些功能将字符串转换为数字(如果它对您的应用程序至关重要)。

    从 DOCS 中,您不能将其设置为任何 undefined 值:
    鼓励您将所有输入的 defaultValue 设置为非未定义,例如空字符串或 null .

    Link to DOCS

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-10
    • 2021-03-29
    • 1970-01-01
    • 2012-08-19
    • 2021-09-16
    • 1970-01-01
    • 2020-03-08
    • 2020-06-23
    相关资源
    最近更新 更多