简体   繁体   English

react-hook-form 多步表单问题

[英]react-hook-form multi step form issue

I'm working on implementation of a multi step form with react-hook-form and my problem is that input fields do not get reinitialized with the form data when I return to the previous page.我正在使用react-hook-form实现多步表单,我的问题是当我返回上一页时,输入字段不会使用表单数据重新初始化。

I'm using <FormProvider /> component from react-hook-form to inject the form data into the pages and my input components are registered with register method from useFormContext() hook我正在使用react-hook-form <FormProvider />组件将表单数据注入页面,并且我的input组件使用useFormContext()钩子中的register方法register

const CreateAccount = () => {
  const [currentStep, setCurrentStep] = useState(0);

  const methods = useForm<FormData>({
    mode: "onChange",
  });
  const onSubmit = (data) => console.log(data);

  const handleNextStep = () => {
    if (currentStep >= 5) return;
    setCurrentStep(currentStep + 1);
  };
  const handlePreviousStep = () => {
    if (currentStep <= 0) return;
    setCurrentStep(currentStep - 1);
  };

  const renderContent = () => ({
    [RegistrationSteps.UsernameEmail]: <UsernameEmail handleNextStep={handleNextStep} handlePreviousStep={handlePreviousStep} />,
    [RegistrationSteps.Password]: <CreatePassword handleNextStep={handleNextStep} handlePreviousStep={handlePreviousStep} />,
  });

  return (
    <Container maxWidth="sm">
      <FormProvider {...methods}>
        <form onSubmit={methods.handleSubmit(onSubmit)}>
            {renderContent()[currentStep]}
        </form>
      </FormProvider>
    </Container>
  );
};

export default CreateAccount;

Here is what the input fields look like这是输入字段的样子

 const {
    register
  } = useFormContext();


    <TextField
      label="Email"
       {...register("email")}
     />

Even though the form still holds the data in its state, it does not populate into corresponding fields when I switch back and forth between the form pages.即使表单仍保留其状态中的数据,当我在表单页面之间来回切换时,它也不会填充到相应的字段中。

Instead of a single form at a global level, I recommend creating each component in your step as a form with its own instance of useForm() and wrapping steps in a state provider to store data across different steps.我建议将步骤中的每个组件创建为具有自己的useForm()实例的表单,并将步骤包装在状态提供程序中以跨不同步骤存储数据,而不是全局级别的单个表单。 That way, you can assign values to the step forms from the respective state using defaultValues option of useForm on initialization.这样,您可以在初始化时使用useForm defaultValues选项从各个状态为步骤表单分配值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM