createFormControl
이 함수는 전체 폼 상태 구독을 만들며, React 컴포넌트 유무와 관계없이 업데이트를 구독할 수 있게 합니다. React Context API 없이 사용할 수 있습니다.
Props(속성)
| 이름 | 타입 | 설명 |
|---|---|---|
...props | Object | UseFormProps |
반환값
| 이름 | 타입 | 설명 |
|---|---|---|
formControl | Object | useForm 훅의 control 객체 |
control | Object | useController, useFormState, useWatch의 control 객체 |
subscribe | Function | 렌더링 없이 폼 상태 업데이트를 구독하는 함수 |
...returns | Functions | useForm이 반환하는 메서드 |
예시:
const { formControl, control, handleSubmit, register } = createFormControl({
mode: "onChange",
defaultValues: {
firstName: "Bill",
},
})
function App() {
useForm({
formControl,
})
return (
<form onSubmit={handleSubmit((data) => console.log(data))}>
<input {...register("name")} />
<FormState />
<ControlledInput />
</form>
)
}
function FormState() {
const { isDirty } = useFormState({
control, // no longer need context api
})
return isDirty ? <p>Form is dirty.</p> : null
}
function ControlledInput() {
const { field } = useController({
control, // no longer need context api
name: "firstName",
})
return <input {...field} />
}
const { formControl, register } = createFormControl(props)
formControl.subscribe({
formState: {
isDirty: true,
values: true,
},
callback: (formState) => {
if (formState.isDirty) {
// do something here
}
if (formState.values.test.length > 3) {
// do something here
}
},
})
function App() {
const { register } = useForm({
formControl,
})
return (
<form>
<input {...register("test")} />
</form>
)
}