【问题标题】:Reset values from react-hook-form when the form is closed关闭表单时从 react-hook-form 重置值
【发布时间】:2022-01-23 05:12:42
【问题描述】:

具有以下组件:

import { yupResolver } from '@hookform/resolvers/yup';
import { useForm } from 'react-hook-form';
import * as yup from 'yup';

import { useToggle } from '../shared/hooks';
import {
  SubsectionLayout,
  Footer,
  Textarea,
  Input,
  Modal,
  Button
} from '../shared/ui-components';

const schema = yup.object().shape({
  name: yup.string().required(),
  description: yup.string().required()
});

export interface ITask {
  name: string;
  description: string;
}

export function MainComponent() {
  const [isOpened, toggleModal] = useToggle(false);

  const { handleSubmit, register, reset } = useForm({
    resolver: yupResolver(schema)
  });

  const onSubmit = (data: ITask) => {
    console.log('data: ', data);
    toggleModal();
    reset(data);
  };

  return (
    <div>
      <Button onClick={toggleModal} />
      <SubsectionLayout title='test'>
        <Modal
          title='add element'
          open={isOpened}
          onClose={toggleModal}
          footer={
            <Footer onSubmit={handleSubmit(onSubmit)} onCancel={toggleModal} editMode={true} />
          }
        >
          <div>
            <Input
              inputId='calculation-engine-script-name'
              label='name'
              {...register('name')}
            />

            <Textarea label='description' {...register('description')} />
          </div>
        </Modal>
      </SubsectionLayout>
    </div>
  );
}
export default MainComponent;

它有一个按钮,点击它会打开一个模式,用户可以在其中写入 namedescription 字段。

当点击提交按钮时,它必须记录内容(用于测试目的)并关闭模式。

问题是当我再次打开modal时,之前引入的输入还在。

我在onSubmit() 中添加了reset(data),但似乎还不够。

有什么想法吗?

【问题讨论】:

  • 看起来您正在尝试使用提交表单时获得的值重置值。不应该是reset()之类的吗?
  • @RameshReddy 我试过这样但结果相同
  • 你试过reset({ name: '', description: '' });吗?
  • official react-hook-form docs 在“重置提交”中他们只是添加了reset({ ...data });
  • @ShakyaKarunathilake,您的第一条评论有正确的解决方案

标签: javascript reactjs typescript react-hooks react-hook-form


【解决方案1】:

试试reset({ name: '', description: '' });

【讨论】:

    猜你喜欢
    • 2023-04-09
    • 2020-06-06
    • 2021-11-01
    • 2021-12-11
    • 2021-12-10
    • 2021-01-05
    • 2021-08-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多