我正在尝试使用 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
我认为问题在于我在多步骤表单中使用了钩子 - 所以也许这算作不在顶层(当我进入我的多步骤表单时)。
有谁知道如何在这种形式的钩子中使用条件逻辑构造?