3

我正在尝试使用 react-hook-form ,它是一种多步骤形式,其中一个步骤具有条件form field.

该字段的条件是boolean属性为真。如果是真的,我想显示一组与该属性相关的问题。

我找到了这个例子,并且我尝试在我的尝试中遵循它的逻辑,如下所述:

import React, { useEffect } from "react";
import ReactDOM from "react-dom";

import useForm from "react-hook-form";
import { withRouter } from "react-router-dom";
import { useStateMachine } from "little-state-machine";
import updateAction from "./updateAction";




const Techniques = props => {
  const { register, unregister, handleSubmit, setValue, watch, errors } = useForm();
  const { action } = useStateMachine(updateAction);
  const onSubit = data => {
    action(data);
    props.history.push("./ProposalInnovation");
  };

const fundingOffer = watch("fundingOffer");

const CustomInput = React.memo(({ register, unregister, setValue, fundingOffer }) => {
  useEffect(() => {
    register({ fundingOffer });

    return () => unregister(fundingOffer);
  }, [fundingOffer, register, unregister]);
  return <input onChange={e => setValue(fundingOffer, e.target.value)} />;
});

function App() {
  const { register, unregister, handleSubmit, setValue, watch } = useForm();
  const fundingOffer = watch("fundingOffer");


  return (

    <div>
      <form onSubmit={handleSubmit(onSubit)}>

        <label>Test for condition:</label>
        <radio 
          ref={register} 
          name="fundingOffer"

        />

        <label>Conditional Field:</label>
        {fundingOffer == true && (
          <CustomInput {...{ register, unregister, setValue, fundingOffer: false }} />
        )}



        <input type="submit" value="next" />    




      </form>

    </div>  
  );
};
};

export default withRouter(Techniques);

当我在我的代码中尝试此操作时,我收到一条错误消息:

useEffect不能在回调中调用React Hook 。必须在 React 函数组件或自定义 React Hook 函数中调用 React Hooks

我认为问题在于我在多步骤表单中使用了钩子 - 所以也许这算作不在顶层(当我进入我的多步骤表单时)。

有谁知道如何在这种形式的钩子中使用条件逻辑构造?

4

1 回答 1

2

我建议将页面构建到多个路由中,并在每个页面将您的数据提交到本地存储:redux、、mobx等等little-state-machine……最后,您可以将所有数据提交到服务中。

你的路线:

<Routes>
  <Page1 />
  <Page2 />
</Routes>

您的个人页面:

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

  const onSubmit = (data) => {
    // update your data into your store
    props.history.push('/page2')    
  }

  return <form onSubmit={handleSubmit(onSubmit)}>
    <input name="data" ref={register} />
   </form>
}

作为参考,您也可以参考我们的文档网站:

https://react-hook-form.com/advanced-usage#WizardFormFunnel

于 2019-12-31T05:11:23.133 回答