본문으로 건너뛰기

setValue

</> setValue: UseFormSetValue

이 함수를 사용하면 등록된 필드의 값을 동적으로 설정하고 폼 상태를 검증하고 업데이트하는 옵션을 지정할 수 있습니다. 동시에 불필요한 리렌더링을 피합니다.

Props


이름설명
name
string
이름으로 단일 필드 또는 필드 배열을 지정합니다.
value
unknown
필드에 설정할 값입니다. 이 인수는 필수이며 undefined일 수 없습니다.
optionsshouldValidate
boolean
  • 입력이 유효한지 계산할지 여부입니다(errors 구독).
  • 전체 폼이 유효한지 계산할지 여부입니다(isValid 구독).
  • 이 옵션은 전체 폼의 errors가 아니라 지정한 필드의 유효성만 다시 계산합니다.
shouldDirty
boolean
  • defaultValues를 기준으로 입력이 dirty 상태인지 계산할지 여부입니다(dirtyFields 구독).
  • defaultValues를 기준으로 전체 폼이 dirty 상태인지 계산할지 여부입니다(isDirty 구독).
  • 이 옵션은 전체 폼의 dirty 필드가 아니라 지정한 필드 수준에서 dirtyFields를 업데이트합니다.
shouldTouch
boolean
v7.8.0부터 입력 자체를 touched 상태로 설정할지 여부입니다.
delayError
boolean
v7.82.0부터 useForm({ delayError })에서 구성한 지연 시간(밀리초)을 사용하여 발생한 검증 오류 표시를 늦추는 선택적 플래그입니다. shouldValidatetrue로 설정한 경우에만 적용됩니다.

예제


기본

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>
)
}

동영상