Skip to content

控制器

用于受控输入的封装组件

</> Controller:Component

React Hook Form 包含不受控制的组件和原生输入,但是很难避免与外部受控组件(例如 反应选择AntDMUI)一起使用。这个封装器组件将使你更轻松地使用它们。

¥React Hook Form embraces uncontrolled components and native inputs, however it's hard to avoid working with external controlled component such as React-Select, AntD and MUI. This wrapper component will make it easier for you to work with them.

属性

¥Props


下表包含有关 Controller 参数的信息。

¥The following table contains information about the arguments for Controller.

名称类型必需的描述
nameFieldPath你输入的唯一名称。
controlControlcontrol 对象来自调用 useForm。使用 FormProvider 时可选。
renderFunction这是 渲染属性。返回 React 元素并提供将事件和值附加到组件中的功能的函数。这简化了与具有非标准属性名称的外部受控组件的集成。为子组件提供 onChangeonBlurnamerefvalue,以及包含特定输入状态的 fieldState 对象。
defaultValueunknown重要的:无法将 undefined 应用于 defaultValuedefaultValues 应用于 useForm
  • You need to either set defaultValue at the field-level or useForm's defaultValues. undefined is not a valid value.
  • If your form will invoke reset with default values, you will need to provide useForm with defaultValues.
  • Calling onChange with undefined is not valid. You should use null or the empty string as your default/cleared value instead.
rulesObjectregister 选项 格式相同的验证规则,其中包括:

required、min、max、minLength、maxLength、pattern、validate
shouldUnregisterboolean = false`卸载后输入将被取消注册,默认值也将被删除。

注意:与 useFieldArray 一起使用时应避免使用此属性,因为在输入卸载/重新安装和重新排序后会调用 unregister 函数。
disabledboolean = false`disabled 属性将从 field 属性返回。受控输入将被禁用,并且其值将从提交数据中省略。

返回

¥Return


下表包含有关 Controller 生成的属性的信息。

¥The following table contains information about properties which Controller produces.

对象名称名称类型描述
fieldonChange(value: any) => void将输入值发送到库的函数。

它应该分配给输入的 onChange 属性,并且值不应该是 undefined
此 prop 更新 formState,你应该避免手动调用 setValue 或其他与字段更新相关的 API。
fieldonBlur() => void将输入的 onBlur 事件发送到库的函数。它应该分配给输入的 onBlur 属性。
fieldvalueunknown受控组件的当前值。
fielddisabledboolean输入的禁用状态。
fieldnamestring输入的名称正在注册。
fieldrefReact.ref用于将钩子表单连接到输入的引用。将 ref 分配给组件的输入引用,以允许钩子表单聚焦错误输入。
fieldStateinvalidboolean当前输入的状态无效。
fieldStateisTouchedboolean电流控制输入的触摸状态。
fieldStateisDirtyboolean电流控制输入的脏状态。
fieldStateerrorobject此特定输入的错误。
formStateisDirtyboolean用户修改任何输入后设置为 true
  1. Important: Make sure to provide all inputs' defaultValues at the useForm, so hook form can have a single source of truth to compare whether the form is dirty.
  2. File typed input will need to be managed at the app level due to the ability to cancel file selection and FileList object.
formStatedirtyFieldsobject具有用户修改字段的对象。确保通过 useForm 提供所有输入的默认值,以便库可以与 defaultValues
  1. Important: Make sure to provide defaultValues at the useForm, so hook form can have a single source of truth to compare each field's dirtiness.
  2. Dirty fields will not represent as isDirty formState, because dirty fields are marked field dirty at field level rather the entire form. If you want to determine the entire form state use isDirty instead.
进行比较
formStatetouchedFieldsobject包含用户交互过的所有输入的对象。
formStatedefaultValuesobject已设置为 useForm 的 defaultValues 或通过 reset API 更新的 defaultValues 的值。
formStateisSubmittedboolean提交表单后设置为 true。将保持 true,直到调用 reset 方法。
formStateisSubmitSuccessfulboolean表明表单已成功提交,没有任何运行时错误。
formStateisSubmittingbooleantrue(如果当前正在提交表单)。否则为 false
formStateisLoadingbooleantrue 如果表单当前正在加载异步默认值。
重要:该属性仅适用于 async defaultValues
formStatesubmitCountnumber表单提交的次数。
formStateisValidboolean如果表单没有任何错误,则设置为 true

setErrorisValid formState 没有影响,isValid 将始终通过整个表单验证结果派生。
formStateisValidatingboolean验证期间设置为 true
formStateerrorsobject存在字段错误的对象。还有一个 ErrorMessage 组件可以轻松检索错误消息。

示例:

¥Examples:


网络

¥Web

import ReactDatePicker from "react-datepicker"
import { TextField } from "@material-ui/core"
import { useForm, Controller } from "react-hook-form"
type FormValues = {
ReactDatepicker: string
}
function App() {
const { handleSubmit, control } = useForm<FormValues>()
return (
<form onSubmit={handleSubmit((data) => console.log(data))}>
<Controller
control={control}
name="ReactDatepicker"
render={({ field: { onChange, onBlur, value, ref } }) => (
<ReactDatePicker
onChange={onChange} // send value to hook form
onBlur={onBlur} // notify when input is touched/blur
selected={value}
/>
)}
/>
<input type="submit" />
</form>
)
}
import React from "react"
import ReactDatePicker from "react-datepicker"
import { TextField } from "@material-ui/core"
import { useForm, Controller } from "react-hook-form"
function App() {
const { handleSubmit, control } = useForm()
return (
<form onSubmit={handleSubmit((data) => console.log(data))}>
<Controller
control={control}
name="ReactDatepicker"
render={({ field: { onChange, onBlur, value, ref } }) => (
<ReactDatePicker
onChange={onChange}
onBlur={onBlur}
selected={value}
/>
)}
/>
<input type="submit" />
</form>
)
}

React Native

import { Text, View, TextInput, Button, Alert } from "react-native"
import { useForm, Controller } from "react-hook-form"
export default function App() {
const {
control,
handleSubmit,
formState: { errors },
} = useForm({
defaultValues: {
firstName: "",
lastName: "",
},
})
const onSubmit = (data) => console.log(data)
return (
<View>
<Controller
control={control}
rules={{
required: true,
}}
render={({ field: { onChange, onBlur, value } }) => (
<TextInput
placeholder="First name"
onBlur={onBlur}
onChangeText={onChange}
value={value}
/>
)}
name="firstName"
/>
{errors.firstName && <Text>This is required.</Text>}
<Controller
control={control}
rules={{
maxLength: 100,
}}
render={({ field: { onChange, onBlur, value } }) => (
<TextInput
placeholder="Last name"
onBlur={onBlur}
onChangeText={onChange}
value={value}
/>
)}
name="lastName"
/>
<Button title="Submit" onPress={handleSubmit(onSubmit)} />
</View>
)
}

视频

¥Video


以下视频展示了 Controller 的内部结构及其构建方式。

¥The following video showcases what's inside Controller and how its been built.

TIP
  • 使用外部受控组件(例如 MUI、AntD、Chakra UI)时,了解每个 prop 的职责非常重要。控制器通过报告和设置值充当你的输入上的 "spy"。

    ¥It's important to be aware of each prop's responsibility when working with external controlled components, such as MUI, AntD, Chakra UI. Controller acts as a "spy" on your input by reporting and setting value.

    • 更改时:将数据发送回钩子表单

      ¥onChange: send data back to hook form

    • 模糊:报告输入已交互(焦点和模糊)

      ¥onBlur: report input has been interacted (focus and blur)

    • 值:设置输入初始值和更新值

      ¥value: set up input initial and updated value

    • 参考:允许输入聚焦于错误

      ¥ref: allow input to be focused with error

    • 名称:给输入一个唯一的名称以下代码和框演示了用法:

      ¥name: give input an unique name The following codesandbox demonstrate the usages:

    • MUI 和其他组件

      ¥MUI and other components

    • Chakra UI 组件

      ¥Chakra UI components

  • 不要再次输入 register。该组件用于处理注册过程。

    ¥Do not register input again. This component is made to take care of the registration process.

    <Controller
    name="test"
    render={({ field }) => {
    // return <input {...field} {...register('test')} />; ❌ double up the registration
    return <input {...field} /> // ✅
    }}
    />
  • 通过在 onChange 期间转换值来自定义发送到钩子表单的值。

    ¥Customise what value gets sent to hook form by transforming the value during onChange.

    <Controller
    name="test"
    render={({ field }) => {
    // sending integer instead of string.
    return (
    <input
    {...field}
    onChange={(e) => field.onChange(parseInt(e.target.value))}
    />
    )
    }}
    />
React Hook Form 中文网 - 粤ICP备13048890号