关闭表单时从 react-hook-form 重置值
Reset values from react-hook-form when the form is closed
具有以下组件:
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;
它有一个按钮,单击它会打开一个模式,用户可以在其中写入 name
和 description
字段。
单击提交按钮时,它必须记录内容(用于测试目的)并关闭模式。
问题是,当我再次打开模态框时,之前输入的输入框还在。
我在onSubmit()
里面加了reset(data)
,但是好像不够
有什么想法吗?
尝试reset({ name: '', description: '' });
具有以下组件:
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;
它有一个按钮,单击它会打开一个模式,用户可以在其中写入 name
和 description
字段。
单击提交按钮时,它必须记录内容(用于测试目的)并关闭模式。
问题是,当我再次打开模态框时,之前输入的输入框还在。
我在onSubmit()
里面加了reset(data)
,但是好像不够
有什么想法吗?
尝试reset({ name: '', description: '' });