Skip to content

FormProvider

提供 React Context 的组件

该组件将托管上下文对象并允许使用组件订阅上下文并使用 useForm 属性和方法。

¥This component will host context object and allow consuming component to subscribe to context and use useForm props and methods.

属性

¥Props


下表适用于 FormProvideruseFormContext 不接受任何参数。

¥This following table applied to FormProvider, useFormContext accepts no argument.

名称类型描述
...propsObjectFormProvider 需要所有 useForm 方法。
RULES
  • 避免使用嵌套的 FormProvider

    ¥Avoid using nested FormProvider

示例:

¥Examples:


import React from "react"
import { useForm, FormProvider, useFormContext } from "react-hook-form"
export default function App() {
const methods = useForm()
const onSubmit = (data) => console.log(data)
return (
<FormProvider {...methods}>
// pass all methods into the context
<form onSubmit={methods.handleSubmit(onSubmit)}>
<NestedInput />
<input type="submit" />
</form>
</FormProvider>
)
}
function NestedInput() {
const { register } = useFormContext() // retrieve all hook methods
return <input {...register("test")} />
}
React Hook Form 中文网 - 粤ICP备13048890号