コンテンツにスキップ

getValues

フォームの値を取得

</> getValues: (payload?: string | string[]) => Object

フォームの値を読み取るための最適化されたヘルパーです。watchgetValues の違いは、getValues は再レンダリングをトリガーしたり、入力の変更をサブスクライブしたりしないことです。

プロパティ


説明
未定義フォームの値全体を返します。
文字列フォームの値のパスにある値を取得します。
配列フォームの値のパスにある値の配列を返します。


以下の例では、getValues メソッドを呼び出したときに期待される内容を示しています。

<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 /> 全体を無効化できます。こちらにがあります。
  • 初期レンダリングの前に useForm から defaultValues を返します。


import React from "react"
import { useForm } from "react-hook-form"
type FormInputs = {
test: string
test1: string
}
export default function App() {
const { register, getValues } = useForm<FormInputs>()
return (
<form>
<input {...register("test")} />
<input {...register("test1")} />
<button
type="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>
)
}
import { useForm } from "react-hook-form"
export default function App() {
const { register, getValues } = useForm()
return (
<form>
<input {...register("test")} />
<input {...register("test1")} />
<button
type="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>
)
}
import React from "react"
import { useForm } from "react-hook-form"
// Flat input values
type Inputs = {
key1: string
key2: number
key3: boolean
key4: Date
}
export default function App() {
const { register, getValues } = useForm<Inputs>()
getValues()
return <form />
}
// Nested input values
type Inputs1 = {
key1: string
key2: number
key3: {
key1: number
key2: boolean
}
key4: string[]
}
export default function Form() {
const { register, getValues } = useForm<Inputs1>()
getValues()
// function getValues(): Record<string, unknown>
getValues("key1")
// function getValues<"key1", unknown>(payload: "key1"): string
getValues("key2")
// function getValues<"key2", unknown>(payload: "key2"): number
getValues("key3.key1")
// function getValues<"key3.key1", unknown>(payload: "key3.key1"): unknown
getValues<string, number>("key3.key1")
// function getValues<string, number>(payload: string): number
getValues<string, boolean>("key3.key2")
// function getValues<string, boolean>(payload: string): boolean
getValues("key4")
// function getValues<"key4", unknown>(payload: "key4"): string[]
return <form />
}

ご支援ありがとうございます

もしあなたのプロジェクトで React Hook Form が役立つと感じたら、スターをつけたり、応援することを検討してください。