Skip to content

unregister

取消注册非受控/受控输入

</> unregister: (name: string | string[], options) => void

此方法允许你对单个输入或输入数组进行 unregister。它还提供了第二个可选参数,用于在取消注册输入后保持状态。

¥This method allows you to unregister a single input or an array of inputs. It also provides a second optional argument to keep state after unregistering an input.

属性

¥Props


下面的示例显示了调用 unregister 方法时会发生什么。

¥The example below shows what to expect when you invoke the unregister method.

<input {...register('yourDetails.firstName')} />
<input {...register('yourDetails.lastName')} />
类型输入名称
stringunregister("yourDetails"){}
stringunregister("yourDetails.firstName"){ lastName: '' }
string[]unregister(["yourDetails.lastName"])''

选项

¥Options


名称类型描述
keepDirtyboolean在此操作期间,isDirtydirtyFields 将保留。但是,这并不能保证下一次用户输入不会更新 isDirty formState,因为 isDirty 是根据 defaultValues 进行测量的。
keepTouchedboolean注销后,touchedFields 将不再删除该输入。
keepIsValidboolean在此操作期间,isValid 将保留。但是,这并不能保证下一个用户输入不会更新 isValid 以进行模式验证,你必须根据取消注册来调整模式。
keepErrorbooleanerrors 不会更新。
keepValueboolean输入的当前 value 将不会更新。
keepDefaultValuebooleanuseForm 中定义的输入的 defaultValue 将保留。
RULES
  • 此方法将删除输入引用及其值,这意味着内置验证规则也将被删除。

    ¥This method will remove input reference and its value, which means built-in validation rules will be removed as well.

  • 通过 unregister 输入,不会影响模式验证。

    ¥By unregister an input, it will not affect the schema validation.

    const schema = yup
    .object()
    .shape({
    firstName: yup.string().required(),
    })
    .required()
    unregister("firstName") // this will not remove the validation against firstName input
  • 确保卸载具有 register 回调的输入,否则输入将再次注册。

    ¥Make sure you unmount that input which has register callback or else the input will get registered again.

    const [show, setShow] = React.useState(true)
    const onClick = () => {
    unregister("test")
    setShow(false) // make sure to unmount that input so register not invoked again.
    }
    {
    show && <input {...register("test")} />
    }

示例:

¥Examples:


import React, { useEffect } from "react"
import { useForm } from "react-hook-form"
interface IFormInputs {
firstName: string
lastName?: string
}
export default function App() {
const { register, handleSubmit, unregister } = useForm<IFormInputs>()
const onSubmit = (data: IFormInputs) => console.log(data)
React.useEffect(() => {
register("lastName")
}, [register])
return (
<form onSubmit={handleSubmit(onSubmit)}>
<button type="button" onClick={() => unregister("lastName")}>
unregister
</button>
<input type="submit" />
</form>
)
}
import React, { useEffect } from "react"
import { useForm } from "react-hook-form"
export default function App() {
const { register, handleSubmit, unregister } = useForm()
React.useEffect(() => {
register("lastName")
}, [register])
return (
<form>
<button type="button" onClick={() => unregister("lastName")}>
unregister
</button>
<input type="submit" />
</form>
)
}

视频

¥Video