</> getValues:
(payload?: string | string[]) => Object
用于读取表单值的优化助手。watch
和 getValues
的区别在于 getValues
不会触发重新渲染或订阅输入更改。
¥An optimized helper for reading form values. The difference between watch
and getValues
is that getValues
will not trigger re-renders or subscribe to input changes.
属性
¥Props
类型 | 描述 |
---|---|
undefined | 返回整个表单值。 |
string | 获取表单值路径处的值。 |
array | 返回表单值路径处的值的数组。 |
示例:
¥Examples:
下面的示例显示了调用 getValues
方法时会发生什么。
¥The example below shows what to expect when you invoke getValues
method.
<input {...register("root.test1")} /><input {...register("root.test2")} />
名称 | 输出 |
---|---|
getValues() | { root: { test1: '', test2: ''} } |
getValues("root") | { test1: '', test2: ''} |
getValues("root.firstName") | '' |
getValues(["yourDetails.lastName"]) | [''] |
-
禁用的输入将返回为
undefined
。如果你想阻止用户更新输入并仍然保留字段值,可以使用readOnly
或禁用整个<fieldset />。这是 example。¥Disabled inputs will be returned as
undefined
. If you want to prevent users from updating the input and still retain the field value, you can usereadOnly
or disable the entire <fieldset />. Here is an example. -
它将在初始渲染之前从
useForm
返回defaultValues
。¥It will return
defaultValues
fromuseForm
before the initial render.
示例:
¥Examples:
import React from "react"import { useForm } from "react-hook-form"type FormInputs = {test: stringtest1: string}export default function App() {const { register, getValues } = useForm<FormInputs>()return (<form><input {...register("test")} /><input {...register("test1")} /><buttontype="button"onClick={() => {const values = getValues() // { test: "test-input", test1: "test1-input" }const singleValue = getValues("test") // "test-input"const multipleValues = getValues(["test", "test1"]) // ["test-input", "test1-input"]}}>Get Values</button></form>)}