react + antd 封装通过json数组形式的Form表单
最近在搞react + antd,在弄form表单的时候,觉得没写一次都要重新写一次Form, Form.Item,感觉有些麻烦;就想啊,能不能像vue+element那样通过json配置的方式,实现一个form组件
1. 假设你已经安装好了依赖,已经可以通过react + antd搭建页面了
以下是我的项目主要依赖,版本不同,写法可能也有些不同:
"react": "^18.1.0",
"react-dom": "^18.1.0",
"antd": "^3.26.19",
"react-router": "^3.2.0",
2.搭建Form组件模子
import React from "react"
import {
Form, Col, Row} from "antd"
class Index extends React.Component {
render() {
return (
<Form>
</Form>
)
}
}
export default Form.create()(Index)
3. 老生长谈的,配合Row与Col组件
主要是用 Col来做Form.Item的容器
const Item = Form.Item
class Index extends React.Component {
//这个地方就是我们用来遍历父组件传过来的json数组配置,我们就定义这个配置属性是fields
getFormField = () => {
//这里要注意以下 form是通过Form.create()(xxx)
const {
form, getFieldDecorator, fields} = this.props
return fields.map((item, index)=>(
<Col key={
item.field + item.label + index} >
<Item label={
item.label}>
{
getFieldDecorator(item.field, {
//...表单项配置
})(
//表单项配置
)
}
</Item>
</Col>
))
}
render() {
return (
<Form>
<Row gutter={
<