useParentForm
Description
Used to read the nearest Form or ObjectField instance, mainly making it convenient to call submit/validate on sub-forms.
Signature
ts
import type { Form, ObjectField } from '@silver-formily/core'
declare function useParentForm(): Form | ObjectFieldUsage
tsx
import { createForm } from '@silver-formily/core'
import { FormProvider, ObjectField, observer, useParentForm, VoidField } from '@silver-formily/react'
import { Typography } from 'antd'
// useParentForm 返回最近的 Form 或 ObjectField,方便调用 submit / validate
const Custom = observer(() => {
const parent = useParentForm()
return (
<p>
<Typography.Text>
{parent?.displayName}
</Typography.Text>
</p>
)
})
const form = createForm()
export default function Demo() {
return (
<FormProvider form={form}>
<ObjectField name="object">
<Custom />
</ObjectField>
<Custom />
<VoidField name="void">
<Custom />
</VoidField>
</FormProvider>
)
}tsx
import { createForm } from '@silver-formily/core'
import { FormProvider, ObjectField, observer, useParentForm, VoidField } from '@silver-formily/react'
import { Typography } from 'antd'
// useParentForm 返回最近的 Form 或 ObjectField,方便调用 submit / validate
const Custom = observer(() => {
const parent = useParentForm()
return (
<p>
<Typography.Text>
{parent?.displayName}
</Typography.Text>
</p>
)
})
const form = createForm()
export default function Demo() {
return (
<FormProvider form={form}>
<ObjectField name="object">
<Custom />
</ObjectField>
<Custom />
<VoidField name="void">
<Custom />
</VoidField>
</FormProvider>
)
}
查看源码
The search starts at the current field: if it is an ObjectField, the hook returns that field itself; otherwise it walks up to the nearest ObjectField and falls back to the current form.