【发布时间】:2020-10-08 09:29:21
【问题描述】:
我在这里把我的问题写成一个新的部分。
我制作了一个多步骤表单,其中我有第一个表单中的动态字段,该字段是手动创建密码或只是自动生成。
所以我的多步表单来回运行正常,但我必须将字段传递给主组件,以便它可以检查验证,我也在传递该密码
问题来了
当我通过password 字段时,即使我点击了自动生成的密码,它也会进行验证
我正在传递这样的字段fields: ["uname", "email", "password"], //to support multiple fields form
所以即使不检查让我创建密码也需要验证。
当我单击让我创建密码并输入一些值然后单击下一步时,当我返回时,输入字段再次设置为隐藏到其初始状态,我知道它为什么会发生,因为当我回来时它会采用初始状态再次声明。
我现在已经厌倦了这个东西,我尝试了很多东西,但没有工作下面是我的代码
import React, { useState, useEffect } from "react";
import Form1 from "./components/Form1";
import Form2 from "./components/Form2";
import Form3 from "./components/Form3";
import { useForm } from "react-hook-form";
function MainComponent() {
const { register, triggerValidation, errors, getValues } = useForm();
const [defaultValues, setDefaultValues] = useState({});
const forms = [
{
fields: ["uname", "email", "password"], //to support multiple fields form
component: (register, errors, defaultValues) => (
<Form1
register={register}
errors={errors}
defaultValues={defaultValues}
/>
)
},
{
fields: ["lname"],
component: (register, errors, defaultValues) => (
<Form2
register={register}
errors={errors}
defaultValues={defaultValues}
/>
)
},
{
fields: [""],
component: (register, errors, defaultValues) => (
<Form3
register={register}
errors={errors}
defaultValues={defaultValues}
/>
)
}
];
const [currentForm, setCurrentForm] = useState(0);
const moveToPrevious = () => {
setDefaultValues(prev => ({ ...prev, ...getValues() }));
triggerValidation(forms[currentForm].fields).then(valid => {
if (valid) setCurrentForm(currentForm - 1);
});
};
const moveToNext = () => {
setDefaultValues(prev => ({ ...prev, ...getValues() }));
triggerValidation(forms[currentForm].fields).then(valid => {
if (valid) setCurrentForm(currentForm + 1);
});
};
const prevButton = currentForm !== 0;
const nextButton = currentForm !== forms.length - 1;
const handleSubmit = e => {
console.log("whole form data - ", JSON.stringify(defaultValues));
};
return (
<div>
<div class="progress">
<div>{currentForm}</div>
</div>
{forms[currentForm].component(
register,
errors,
defaultValues[currentForm]
)}
{prevButton && (
<button
className="btn btn-primary"
type="button"
onClick={moveToPrevious}
>
back
</button>
)}
{nextButton && (
<button className="btn btn-primary" type="button" onClick={moveToNext}>
next
</button>
)}
{currentForm === 2 && (
<button
onClick={handleSubmit}
className="btn btn-primary"
type="submit"
>
Submit
</button>
)}
</div>
);
}
export default MainComponent;
请在此处查看我的代码沙箱,您可以找到完整的工作代码Code sandbox
【问题讨论】:
标签: javascript reactjs react-hooks react-hook-form