You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

react-hook-form:如何让reset函数仅清空指定Controller字段

解决react-hook-form中reset仅清空指定字段的问题

调用reset({ state: '' })时,react-hook-form默认会将未在参数中声明的字段重置为undefined,这就是country字段被意外清空的原因。以下是三种实现仅清空state字段的可行方案:

方案一:使用setValue单独更新字段

直接通过setValue方法设置state为空字符串,不会影响其他字段的当前值:

setValue('state', '');

方案二:结合getValues保留其他字段值

先通过getValues获取当前表单的完整值,仅修改state字段后传入reset,以此保留country的现有值:

reset({
  ...getValues(),
  state: ''
});

方案三:利用reset的配置参数

调用reset时传入第二个参数{ keepDirtyValues: true },该配置会保留所有已修改过的字段值,仅重置你指定的字段:

reset({ state: '' }, { keepDirtyValues: true });

完整代码示例

import { useForm, Controller } from 'react-hook-form';
import Select from '你的Select组件路径';

function YourForm() {
  const { control, setValue, reset, getValues } = useForm();

  // 任选一种方案实现
  const clearState = () => {
    setValue('state', '');
  };

  return (
    <>
      <Controller 
        name='country'
        control={control}
        render={({ field }) => <Select {...field} />}
      />
      <Controller 
        name='state'
        control={control}
        render={({ field }) => <Select {...field} />}
      />
      <button onClick={clearState}>仅清空state</button>
    </>
  );
}

内容的提问来源于stack exchange,提问作者Lucas Eduardo Gomes

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 20:02:46