getFieldState
</> getFieldState: UseFormGetFieldState v7.25.0부터
이 메서드는 개별 필드 상태를 반환합니다. 중첩된 필드 상태를 타입 안전하게 가져올 때 유용합니다.
Props(속성)
| 이름 | 타입 | 설명 |
|---|---|---|
name | string | 등록된 필드 이름입니다. |
| formState | object | 선택적인 prop입니다. formState를 useForm, useFormContext, useFormState를 통해 읽거나 구독하지 않은 경우에만 필요합니다. 자세한 내용은 아래 규칙을 참고하세요. |
반환값
| 이름 | 타입 | 설명 |
|---|---|---|
isDirty | boolean | 필드가 수정되었습니다. 조건: dirtyFields를 구독합니다. |
| isTouched | boolean | 필드에 포커스와 블러 이벤트가 발생했습니다. 조건: touchedFields를 구독합니다. |
| invalid | boolean | 필드가 유효하지 않습니다. 조건: errors를 구독합니다. |
| isValidating | boolean | v7.51.0부터 필드를 현재 검증하고 있습니다. 조건: isValidating을 구독합니다. |
| error | undefined | FieldError | 필드 오류 객체입니다. 조건: errors를 구독합니다. |
예시
import { useForm } from "react-hook-form"
export default function App() {
const {
register,
getFieldState,
formState: { isDirty, isValid },
} = useForm({
mode: "onChange",
defaultValues: {
firstName: "",
},
})
// you can invoke before render or within the render function
const fieldState = getFieldState("firstName")
return (
<form>
<input {...register("firstName", { required: true })} />{" "}
<p>{getFieldState("firstName").isDirty && "dirty"}</p>{" "}
<p>{getFieldState("firstName").isTouched && "touched"}</p>
<button
type="button"
onClick={() => console.log(getFieldState("firstName"))}
>
field state
</button>
</form>
)
}