react-hook-form - 每次提交后清空输入字段

问题描述 投票:0回答:6

我试图了解react-hook-form是如何工作的。 为此,我创建了以下示例:

import React from 'react';
import { useForm } from 'react-hook-form';

const InputForm = () => {
  const { register, handleSubmit } = useForm();

  const onSubmit = (data) => {
    console.log(data);
  };

  return (
    <>
      <Form onSubmit={handleSubmit(onSubmit)}>
        <Form.Group controlId='formBasicName'>
          <Form.Label>Name</Form.Label>
          <Form.Control
            type='text'
            name='name'
            ref={register}
          />
        </Form.Group>

        <Form.Group controlId='formBasicEmail'>
          <Form.Label>Email address</Form.Label>
          <Form.Control
            type='email'
            name='email'
            ref={register}
          />
          
        <Button className='submitBtn' type='submit'>
          Submit
        </Button>
      </Form>
    </>
  );
};

export default InputForm;

它有效,如果我提交表单,我可以在控制台中看到数据对象。 唯一的问题是每次提交后输入框仍然显示它们的值。 我希望每次提交后输入框的值变空。 使用 useState 会很容易,但现在我正在使用react-hook-from,我不知道该怎么做。

reactjs react-hooks
6个回答
35
投票
const InputForm = () => {
  const { register, handleSubmit, reset } = useForm();

  const onSubmit = (data) => {
    //...
    reset();
  };

添加到提交功能


14
投票

使用此提交功能:

const onSubmit = (data, e) => {
  e.target.reset();
};


13
投票

请不要接受之前的答案 - RHF 文档(请参阅规则和

Submit With Reset
选项卡) 不批准
reset
回调中的
onSubmit

建议不要在 onReset 或 onSubmit 回调中调用重置。

正确的方法是让

useEffect
在所有异步工作完成后更新:

const { reset } = useForm();
const [isSafeToReset, setIsSafeToReset] = useState(false);
  
useEffect(() => {
   if (!isSafeToReset) return;

   reset(result); // asynchronously reset your form values
}, [reset])

const onSubmit = async (data, e) => {
    try {
      await fetch('./api/formValues.json'); 
      setIsSafeToReset(true);
    } catch (e) {
      // do something w Err
    }
};


6
投票

React Hook Forms v7。这将清除表单数据。

    const {register, handleSubmit, formState: { errors }, reset} = useForm();

    const onSubmit = (data, e) => {
        console.log(data)
        reset('', {
            keepValues: false,
        })
    }

0
投票

使用以下代码重置输入字段

const onSubmit = (data, e) => {
  e.target[0].value = ''; // for name
  e.target[1].value = '';  // for email
};

0
投票

//use resetField function 

const { register, handleSubmit, resetField } = useForm();
const onSubmit = async (data) => {
    console.log(data);
      resetField('fieldname');
   
    } 

© www.soinside.com 2019 - 2024. All rights reserved.