组件概述
MForm 是一个高度可配置的动态表单组件,基于 Ant Design 的 Form 组件封装,支持多种表单控件类型和灵活的布局配置。组件通过 JSON 配置驱动,可快速构建复杂的表单界面。
核心文件结构
├── index.tsx # 主组件文件
├── MFormItemConst.tsx # 表单控件类型映射和渲染逻辑
└── type.ts # 类型定义和接口
| 属性名 |
类型 |
默认值 |
描述 |
| column |
1 \| 2 \| 3 \| 4 |
1 |
表单列数布局 |
| formItems |
IMFormItem[] |
- |
表单项配置数组(必填) |
| form |
FormInstance |
- |
Antd Form 实例 |
| formProps |
FormProps |
- |
Antd Form 组件的其他属性 |
| itemLayout |
{ labelCol?: MFormItemLayout; wrapperCol?: MFormItemLayout } |
{ labelCol: { span: 7 }, wrapperCol: { span: 17 } } |
表单项布局配置 |
| formRowProps |
RowProps |
- |
Antd Row 组件的其他属性 |
| 类型 |
描述 |
对应组件 |
| Input |
文本输入框 |
Input |
| Password |
密码输入框 |
Input.Password |
| Text |
文本域 |
Input.TextArea |
| InputNumber |
数字输入框 |
InputNumber |
| Select |
下拉选择框 |
Select |
| Radio |
单选按钮组 |
Radio.Group |
| Checkbox |
多选框组 |
Checkbox.Group |
| DatePicker |
日期选择器 |
DatePicker |
| RangePicker |
日期范围选择器 |
DatePicker.RangePicker |
| Upload |
文件上传 |
Upload |
| Mentions |
提及输入框 |
Mentions |
| Cascader |
级联选择器 |
Cascader |
| TreeSelect |
树形选择器 |
TreeSelect |
| 属性名 |
类型 |
必填 |
描述 |
| id |
string |
是 |
表单字段名 |
| label |
string |
是 |
表单项标签 |
| type |
MFormItemTypeEnum |
是 |
表单控件类型 |
| disabled |
boolean |
- |
是否禁用 |
| initialValue |
any |
- |
初始值 |
| required |
string |
- |
必填校验提示信息(设置后会自动添加 required 校验规则) |
| rules |
FormRule[] |
- |
校验规则 |
| render |
(form?: FormInstance) => ReactElement |
- |
自定义渲染函数(优先级高于 type) |
| formItemProps |
FormItemProps |
- |
Antd Form.Item 的其他属性 |
| itemLayout |
{ labelCol?: MFormItemLayout; wrapperCol?: MFormItemLayout } |
- |
当前项布局配置(覆盖全局配置) |
| span |
number |
- |
当前项所占列宽(1-24,默认 24/column) |
| show |
boolean |
默认 true |
是否显示当前表单项 |
| props |
any |
- |
表单控件的其他属性 |
| prefix |
React.ReactNode |
- |
表单控件前的内容 |
| suffix |
React.ReactNode |
- |
表单控件后的内容 |
使用示例
基本表单
<MForm
formItems={[
{
id: 'username',
label: '用户名',
type: MFormItemTypeEnum.Input,
required: '请输入用户名',
maxLength: 20,
},
{
id: 'password',
label: '密码',
type: MFormItemTypeEnum.Password,
required: '请输入密码',
},
]}
/>
多列布局
<MForm
column={2}
formItems={[
{
id: 'name',
label: '姓名',
type: MFormItemTypeEnum.Input,
span: 12,
},
{
id: 'age',
label: '年龄',
type: MFormItemTypeEnum.InputNumber,
span: 12,
},
]}
/>
复杂表单
<MForm
column={3}
formItems={[
{
id: 'gender',
label: '性别',
type: MFormItemTypeEnum.Radio,
props: {
options: [
{ label: '男', value: 'male' },
{ label: '女', value: 'female' },
],
},
prefix: <div style={{ height: 100, width: 100 }}>前置内容宽高100</div>,
suffix: (
<div>
后置内容 <Button>一键复制</Button>
</div>
),
},
{
id: 'birthday',
label: '出生日期',
type: MFormItemTypeEnum.DatePicker,
placeholder: '请选择出生日期',
},
{
id: 'avatar',
label: '头像上传',
type: MFormItemTypeEnum.Upload,
props: {
action: '/upload',
maxCount: 1,
},
},
]}
/>
自定义渲染
<MForm
formItems={[
{
id: 'custom',
label: '自定义字段',
render: form => (
<Input
addonBefore='http://'
addonAfter='.com'
onChange={e => form.setFieldValue('custom', e.target.value)}
/>
),
},
]}
/>