setValue
</> setValue: UseFormSetValue
이 함수를 사용하면 등록된 필드의 값을 동적으로 설정하고 폼 상태를 검증하고 업데이트하는 옵션을 지정할 수 있습니다. 동시에 불필요한 리렌더링을 피합니다.
Props
| 이름 | 설명 | |
|---|---|---|
namestring | 이름으로 단일 필드 또는 필드 배열을 지정합니다. | |
valueunknown | 필드에 설정할 값입니다. 이 인수는 필수이며 undefined일 수 없습니다. | |
options | shouldValidateboolean |
|
shouldDirtyboolean |
| |
shouldTouchboolean | v7.8.0부터 입력 자체를 touched 상태로 설정할지 여부입니다. | |
delayErrorboolean | v7.82.0부터 useForm({ delayError })에서 구성한 지연 시간(밀리초)을 사용하여 발생한 검증 오류 표시를 늦추는 선택적 플래그입니다. shouldValidate도 true로 설정한 경우에만 적용됩니다. |
예제
기본
import { useForm } from "react-hook-form"
const App = () => {
const { register, setValue } = useForm({
firstName: "",
})
return (
<form>
<input {...register("firstName", { required: true })} />
<button onClick={() => setValue("firstName", "Bill")}>setValue</button>
<button
onClick={() =>
setValue("firstName", "Luo", {
shouldValidate: true,
shouldDirty: true,
})
}
>
setValue options
</button>
</form>
)
}
오류 지연
// the actual delay (in ms) is configured once at the form level
const { setValue } = useForm({ delayError: 500 })
setValue("firstName", "Bill", {
delayError: true, // opt in to the 500ms delay configured above
shouldValidate: true,
})
종속 필드
import { useEffect } from "react"
import { useForm } from "react-hook-form"
type FormValues = {
a: string
b: string
c: string
}
export default function App() {
const { watch, register, handleSubmit, setValue, formState } =
useForm<FormValues>({
defaultValues: {
a: "",
b: "",
c: "",
},
})
const onSubmit = (data: FormValues) => console.log(data)
const [a, b] = watch(["a", "b"])
useEffect(() => {
if (formState.touchedFields.a && formState.touchedFields.b && a && b) {
setValue("c", `${a} ${b}`)
}
}, [setValue, a, b, formState])
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input {...register("a")} placeholder="a" />
<input {...register("b")} placeholder="b" />
<input {...register("c")} placeholder="c" />
<input type="submit" />
<button
type="button"
onClick={() => {
setValue("a", "what", { shouldTouch: true })
setValue("b", "ever", { shouldTouch: true })
}}
>
trigger value
</button>
</form>
)
}