外部调用
// const dataSourceTest = [
// {
// label: 'label1',
// id: 'label1',
// type: 'isInput',
// placeholder: '请输入指标分类',
// },
// {
// label: 'label2',
// id: 'label2',
// type: 'isSelect',
// showSearch: 'true',
// selectKey: 'id',
// selectLabel: 'show',
// selectList: [ { id: 1, show: '哈哈哈' } ],
// placeholder: '请输入指标分类',
// },
// {
// label: 'label3',
// id: 'label3',
// type: 'isRangePicker',
// rules: [
// {
// required: true,
// message: '请输入',
// },
// ],
// },
// ]
<Form>
<GetFormItem
dataSource={dataSourceTest}
form={this.props.form}
/>
</Form>
GetFormItem.js文件
import React from 'react'
import { Select, Input, Form, DatePicker, Radio } from 'antd'
const { RangePicker } = DatePicker
const { Option } = Select
// 返回指定类型的dom
const getDomType = (item) => {
const {
type, // dom类型
placeholder,
list = [],
disabled,
customKey, // 自定义指定key和value
customLabel, // 自定义指定显示的label
selectMode, // 下拉类型
allowClear = true,
showSearch = true,
optionFilterProp = 'children',
} = item
const strategy = {
isInput: () => <Input
allowClear={allowClear}
placeholder={placeholder}
disabled={disabled} />,
isSelect: () => (
<Select
allowClear={allowClear}
showSearch={showSearch}
optionFilterProp={optionFilterProp}
placeholder={placeholder}
mode={selectMode}
disabled={disabled}
>
{list.map((el) => (
<Option
value={el[customKey] || el.id}
key={el[customKey] || el.id}>
{el[customLabel] || el.label}
</Option>
))}
</Select>
),
isRangePicker: () => (
<RangePicker
format='YYYY-MM-DD'
allowClear={allowClear}/>
),
isRadio: () => (
<Radio.Group>
{list.map((el) => (
<Radio
value={el[customKey] || el.id}
key={el[customKey] || el.id}>{el[customLabel] || el.label}</Radio>
))}
</Radio.Group>
),
}
return strategy[type]()
}
const GetFormItem = (props) => {
const { form, dataSource, formItemLayout, editVal = {} } = props
const { getFieldDecorator } = form
return (
<>
{
dataSource.map(item =>
<Form.Item
label={item.label}
key={item.id}
{...formItemLayout}>
{getFieldDecorator(item.id, {
rules: item.rules,
initialValue: editVal[item.id],
})(getDomType(item))}
</Form.Item>,
)
}
</>
)
}
export default GetFormItem