ArrayField
描述
作为 @silver-formily/core 中 createArrayField 的 React 实现,它是专门用于将 ViewModel 与输入控件做绑定的桥接组件,ArrayField 组件属性参考 IFieldFactoryProps
name 属性必填。可使用 render props 或自定义 component 渲染列表,也接受普通 ReactNode。
用例
tsx
import { createForm } from '@silver-formily/core'
import { ArrayField, Field, FormProvider } from '@silver-formily/react'
import { Button, Input, Space } from 'antd'
const form = createForm()
export default function Demo() {
return (
<FormProvider form={form}>
<ArrayField name="array">
{field => (
<div>
{(field.value || []).map((item, index) => (
<div
key={`${item.id}-${index}`}
style={{ marginBottom: 10 }}
>
<Space>
<Field name={`${index}.value`} component={[Input]} />
<Button onClick={() => field.remove(index)}>
Remove
</Button>
<Button onClick={() => field.moveUp(index)}>
Move Up
</Button>
<Button onClick={() => field.moveDown(index)}>
Move Down
</Button>
</Space>
</div>
))}
<Button onClick={() => field.push({ id: Date.now(), value: '' })}>
Add
</Button>
</div>
)}
</ArrayField>
</FormProvider>
)
}tsx
import { createForm } from '@silver-formily/core'
import { ArrayField, Field, FormProvider } from '@silver-formily/react'
import { Button, Input, Space } from 'antd'
const form = createForm()
export default function Demo() {
return (
<FormProvider form={form}>
<ArrayField name="array">
{field => (
<div>
{(field.value || []).map((item, index) => (
<div
key={`${item.id}-${index}`}
style={{ marginBottom: 10 }}
>
<Space>
<Field name={`${index}.value`} component={[Input]} />
<Button onClick={() => field.remove(index)}>
Remove
</Button>
<Button onClick={() => field.moveUp(index)}>
Move Up
</Button>
<Button onClick={() => field.moveDown(index)}>
Move Down
</Button>
</Space>
</div>
))}
<Button onClick={() => field.push({ id: Date.now(), value: '' })}>
Add
</Button>
</div>
)}
</ArrayField>
</FormProvider>
)
}
查看源码
API
属性基于 Field,但 children 回调中的字段类型为 ArrayField。完整公共属性参见 Field。
ts
import type { ArrayField as Model } from '@silver-formily/core'
import type { IFieldProps, JSXComponent } from '@silver-formily/react'
type Props<D extends JSXComponent, C extends JSXComponent> = IFieldProps<D, C, Model>