Skip to content

useFormContext

用于钩子表单的 React Context API

</> useFormContext: Function

此自定义钩子允许你访问表单上下文。useFormContext 旨在用于深度嵌套结构,在这种结构中将上下文作为 prop 传递会变得不方便。

¥This custom hook allows you to access the form context. useFormContext is intended to be used in deeply nested structures, where it would become inconvenient to pass the context as a prop.

返回

¥Return


该钩子将返回所有 useForm 返回方法和属性。

¥This hook will return all the useForm return methods and props.

const methods = useForm()
<FormProvider {...methods} /> // all the useForm return props
const methods = useFormContext() // retrieve those props
RULES

你需要使用 FormProvider 组件封装表单,useFormContext 才能正常工作。

¥You need to wrap your form with the FormProvider component for useFormContext to work properly.

示例:

¥Example:

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号