在开发中,如果页面有大量的相同功能及UI,我们可以封装成组件复用,以便能减少开发工作量,并能有效的进行统一维护。举个例子,我页面中有大量这种功能,接下来就进行组件的封装
根据截图可知,功能主要分为两大块,搜索模块 + table结果展示模块
因此,先创建一个公共组件,主要代码如下,formList是头部搜索部分,根据不同页面需要的搜索项进行设置即可
constructor部分
constructor() {
super()
this.state = {
formList: [
{
name: 'code',
type: 'input',
placeholder: '姓名'
},
{
name: 'name',
type: 'input',
placeholder: '年龄'
},
{
name: 'type',
type: 'select',
placeholder: '爱好',
selectList: [
{
name: '一类',
id: 0
},
{
name: '二类',
id: 1
}
]
},
{
name: 'isDepaAdd',
type: 'select',
placeholder: '请选择添加',
selectList: [
{
name: '可添加',
id: 1
},
{
name: '不可添加',
id: 0
}
]
}
]
}
}
render 部分
<Form
name="advanced_search"
className="ant-advanced-search-form"
onFinish={this.handleSearch}
>
<Row gutter={24}>
{getFields()}
<Col span={6} style={{ textAlign: 'left'}}>
<Button type="primary" htmlType="submit">
查询
</Button>
</Col>
</Row>
</Form>
js(render中getFields)功能部分,根据type,决定显示input、select、cascader、rangePicker等组件
const getFields = () => {
const children = [];
formList.map((item, index) => {
children.push(
<Col span={6} key={index}>
<Form.Item name={item.name}>
{
item.type === 'input' ?
<Input placeholder={item.placeholder} />
:
item.type === 'select' ?
<Select placeholder={item.placeholder}>
<Option value="">全部</Option>
{
item.selectList.length && item.selectList.map(v => {
return (
<Option value={v.id} key={v.id}>{v.name}</Option>
)
})
}
</Select>
:
item.type === 'cascader'
?
<Cascader
options={item.optionList}
onChange={(e) => this.onChangeRegions(e, item)}
placeholder={item.placeholder}
changeOnSelect
/>
:
<RangePicker placeholder={item.placeholder} />
}
</Form.Item>
</Col>,
);
})
return children;
};
至此search部分封装完成,table部分也是如此,贴上代码
this.state = {
tableData: {
loading: false,
columns: [
{ title: '编码', dataIndex: 'code'},
{ title: '名称', dataIndex: 'name' },
{ title: '类型', dataIndex: 'type', render: (text) => (text === 1) ? '一类' : '二类' },
{ title: '创建时间', dataIndex: 'createTime' },
{
title: '操作',
dataIndex: '',
key: 'action',
width: 160,
responsive: ['md'],
render: (record) => <p>
<Button type="primary" size="small" style={{marginLeft: 8}} onClick={() => this.handleEdit(record)}>编辑</Button>
<Button type="danger" size="small" style={{marginLeft: 8}} onClick={() => this.handleDelete(record)}>删除</Button>
</p>,
},
],
data: [],
paginationParams: {
pageSize: 10,
current: 1,
total: 0,
showSizeChanger: true
}
}
}
<Table
className={'table'}
bordered
columns={columns}
dataSource={data}
loading={l
oading}
pagination={paginationParams}
onChange={this.getList}
style={{marginTop: 16}}
/>