我是一个刚做出反应的人,我陷入了困境。我当前正在开发的应用程序有多个部分,例如第 1 部分、第 2 部分……每个部分都有包含不同字段的表单。我需要在子组件中验证父组件中存在的表单。
function App() {
return <>
//section 1 code here
<section 2/>
<section 3/>
<section 4/>
</>
}
有没有一种方法可以将第 1 部分的表单数据传递到第 2 部分,并在单击第 2 部分中的按钮时验证数据。 形成第 2 部分到第 3 部分的数据,并在第 3 部分中单击按钮时验证数据。 ...其他部分
我正在使用 React hook 表单和 usefieldarray 来添加和删除字段(动态)
您应该能够通过在父组件级别管理表单数据和验证并将必要的数据和函数传递给子组件来实现这一点。由于您使用的是 React Hook Form,因此可以使用 useForm hook 来管理表单状态和验证。
像这样的东西应该有效,
import { useForm, useFieldArray } from 'react-hook-form'
function App() {
const { control, handleSubmit, setValue, watch, formState: { errors } } = useForm({
// Your initial form values go here...
})
const { fields, append, remove } = useFieldArray({
control,
name: 'yourFieldName',
})
const onSubmitSection1 = (data) => {
// Handle validation logic for section 1 if needed
// Set form data for section 1
setValue('yourFieldName', data.yourFieldName)
// Move to section 2
// You can add more logic here if needed
}
const onSubmitSection2 = (data) => {
// Handle validation logic for section 2 if needed
// Set form data for section 2
setValue('yourFieldName', data.yourFieldName)
// Move to section 3
// You can add more logic here if needed...
}
// Repeat this pattern for other sections as needed
return (
<>
// Section 1
<form onSubmit={handleSubmit(onSubmitSection1)}>
// Your form fields for section 1
{fields.map((item, index) => (
// Render your form fields using React Hook Form methods
// For example, use `Controller` for each field
))}
// Button to move to section 2
<button type="submit">Next</button>
</form>
// Section 2
{watch('yourFieldName') && (
<form onSubmit={handleSubmit(onSubmitSection2)}>
// Your form fields for section 2
{fields.map((item, index) => (
// Render your form fields using React Hook Form methods
))}
// Button to move to section 3
<button type="submit">Next</button>
</form>
)}
// Repeat similar pattern for other sections
</>
)
}
export default App