Skip to content

setValue

更新字段值

</> setValue: (name: string, value: unknown, config?: SetValueConfig) => void

此函数允许你动态设置 registered 字段的值,并可以选择验证和更新表单状态。同时,它会尝试避免不必要的重新渲染。

¥This function allows you to dynamically set the value of a registered field and have the options to validate and update the form state. At the same time, it tries to avoid unnecessary rerender.

属性

¥Props


名称描述
name
string
按名称定位单个字段或字段数组。
value
unknown
字段的值。此参数是必需的,不能是 undefined
optionsshouldValidate
boolean
  • Whether to compute if your input is valid or not (subscribed to errors).
  • Whether to compute if your entire form is valid or not (subscribed to isValid).
  • This option will update touchedFields at the specified field level not the entire form touched fields.
shouldDirty
boolean
  • Whether to compute if your input is dirty or not against your defaultValues (subscribed to dirtyFields).
  • Whether to compute if your entire form is dirty or not against your defaultValues (subscribed to isDirty).
  • This option will update dirtyFields at the specified field level not the entire form dirty fields.
shouldTouch
boolean
是否将输入本身设置为可触摸。
RULES
  • 你可以对字段数组使用诸如 replaceupdate 之类的方法,但是,它们会导致组件卸载并重新安装目标字段数组。

    ¥You can use methods such as replace or update for field array, however, they will cause the component to unmount and remount for the targeted field array.

    const { update } = useFieldArray({ name: "array" })
    // unmount fields and remount with updated value
    update(0, { test: "1", test1: "2" })
    // will directly update input value
    setValue("array.0.test1", "1")
    setValue("array.0.test2", "2")
  • 当定位不存在的字段时,该方法不会创建新字段。

    ¥The method will not create a new field when targeting a non-existing field.

    const { replace } = useFieldArray({ name: "test" })
    // ❌ doesn't create new input
    setValue("test.101.data")
    // ✅ work on refresh entire field array
    replace([{ data: "test" }])
  • 只有以下情况才会触发重新渲染:

    ¥Only the following conditions will trigger a re-render:

    • 当值更新触发或更正错误时。

      ¥When an error is triggered or corrected by a value update.

    • setValue 导致状态更新时,例如 dirty 和 touched。

      ¥When setValue cause state update, such as dirty and touched.

  • 建议定位字段的名称,而不是将第二个参数设为嵌套对象。

    ¥It's recommended to target the field's name rather than make the second argument a nested object.

    setValue("yourDetails.firstName", "value") // ✅ performant
    setValue("yourDetails", { firstName: "value" })// less performant
    register("nestedValue", { value: { test: "data" } }) // register a nested value input
    setValue("nestedValue.test", "updatedData") // ❌ failed to find the relevant field
    setValue("nestedValue", { test: "updatedData" }) // ✅ setValue find input and update
  • 建议在调用 setValue 之前注册输入的名称。要更新整个 FieldArray,请确保首先执行 useFieldArray 钩子。

    ¥It's recommended to register the input's name before invoking setValue. To update the entire FieldArray, make sure the useFieldArray hook is being executed first.

    重要的:改用 useFieldArray 中的 replace,在下一个主要版本中将删除使用 setValue 更新整个字段数组。

    ¥Important: use replace from useFieldArray instead, update entire field array with setValue will be removed in the next major version.

    // you can update an entire Field Array,
    setValue("fieldArray", [{ test: "1" }, { test: "2" }]) // ✅
    // you can setValue to a unregistered input
    setValue("notRegisteredInput", "value") // ✅ prefer to be registered
    // the following will register a single input (without register invoked)
    setValue("resultSingleNestedField", { test: "1", test2: "2" }) // 🤔
    // with registered inputs, the setValue will update both inputs correctly.
    register("notRegisteredInput.test", "1")
    register("notRegisteredInput.test2", "2")
    setValue("notRegisteredInput", { test: "1", test2: "2" }) // ✅ sugar syntax to setValue twice

示例

¥Examples


基本

¥Basic

import { useForm } from "react-hook-form"
const App = () => {
const { register, setValue } = useForm({
firstName: "",
})
return (
<form>
<input {...register("firstName", { required: true })} />
<button onClick={() => setValue("firstName", "Bill")}>setValue</button>
<button
onClick={() =>
setValue("firstName", "Luo", {
shouldValidate: true,
shouldDirty: true,
})
}
>
setValue options
</button>
</form>
)
}

依赖字段

¥Dependant Fields

import * as React from "react"
import { useForm } from "react-hook-form"
type FormValues = {
a: string
b: string
c: string
}
export default function App() {
const { watch, register, handleSubmit, setValue, formState } =
useForm<FormValues>({
defaultValues: {
a: "",
b: "",
c: "",
},
})
const onSubmit = (data: FormValues) => console.log(data)
const [a, b] = watch(["a", "b"])
React.useEffect(() => {
if (formState.touchedFields.a && formState.touchedFields.b && a && b) {
setValue("c", `${a} ${b}`)
}
}, [setValue, a, b, formState])
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input {...register("a")} placeholder="a" />
<input {...register("b")} placeholder="b" />
<input {...register("c")} placeholder="c" />
<input type="submit" />
<button
type="button"
onClick={() => {
setValue("a", "what", { shouldTouch: true })
setValue("b", "ever", { shouldTouch: true })
}}
>
trigger value
</button>
</form>
)
}

视频

¥Video