setValues
</> setValues: UseFormSetValues v7.74.0부터
이 함수는 여러 필드 값을 한 번에 동적으로 설정하고, 검증 및 폼 상태 업데이트 여부를 선택할 수 있게 합니다. 현재 폼 값을 받는 콜백 함수도 허용하므로 기존 값에서 다음 상태를 쉽게 도출할 수 있습니다.
Props(속성)
| 이름 | 설명 | |
|---|---|---|
valuePartial<TFieldValues> | (formValues: TFieldValues) => TFieldValues | 업데이트할 필드 값을 담은 객체 또는 현재 폼 값을 받아 다음 폼 값을 반환하는 콜백 함수입니다. 이 인수는 필수입니다. | |
options | shouldValidateboolean |
|
shouldDirtyboolean |
| |
shouldTouchboolean | 업데이트된 입력을 touched 상태로 설정할지 지정합니다. | |
delayErrorboolean | v7.82.0부터 useForm({ delayError })에 설정한 지연 시간(밀리초)을 사용해 검증 오류 표시를 늦추는 선택적 플래그입니다. shouldValidate도 true로 설정한 경우에만 적용됩니다. |
예시
기본 사용법
import { useForm } from "react-hook-form"
const App = () => {
const { register, setValues } = useForm({
defaultValues: {
firstName: "",
lastName: "",
},
})
return (
<form>
<input {...register("firstName")} />
<input {...register("lastName")} />
<button
type="button"
onClick={() => setValues({ firstName: "Bill", lastName: "Luo" })}
>
setValues
</button>
</form>
)
}
콜백(현재 값에서 다음 상태 도출)
import { useForm } from "react-hook-form"
const App = () => {
const { register, setValues } = useForm({
defaultValues: {
name: "",
count: 0,
},
})
return (
<form>
<input {...register("name")} />
<input type="number" {...register("count")} />
<button
type="button"
onClick={() => {
setValues((data) => {
return {
...data,
name: "test",
}
})
}}
>
setValues with callback
</button>
</form>
)
}
옵션 사용
import { useForm } from "react-hook-form"
const App = () => {
const { register, setValues } = useForm({
defaultValues: {
firstName: "",
lastName: "",
},
})
return (
<form>
<input {...register("firstName", { required: true })} />
<input {...register("lastName", { required: true })} />
<button
type="button"
onClick={() =>
setValues(
{ firstName: "Bill", lastName: "Luo" },
{ shouldValidate: true, shouldDirty: true, shouldTouch: true }
)
}
>
setValues with validation
</button>
</form>
)
}