美文网首页reactantd
React JSON Schema Form

React JSON Schema Form

作者: nick121212 | 来源:发表于2018-01-19 17:25 被阅读654次

    最近在用ant design做后台管理系统,表单真是蛋疼的存在。

    下面贴一段截自与ant design官网的代码

    import { Form, Icon, Input, Button } from 'antd';
    const FormItem = Form.Item;
    
    function hasErrors(fieldsError) {
      return Object.keys(fieldsError).some(field => fieldsError[field]);
    }
    
    class HorizontalLoginForm extends React.Component {
      componentDidMount() {
        // To disabled submit button at the beginning.
        this.props.form.validateFields();
      }
      handleSubmit = (e) => {
        e.preventDefault();
        this.props.form.validateFields((err, values) => {
          if (!err) {
            console.log('Received values of form: ', values);
          }
        });
      }
      render() {
        const { getFieldDecorator, getFieldsError, getFieldError, isFieldTouched } = this.props.form;
    
        // Only show error after a field is touched.
        const userNameError = isFieldTouched('userName') && getFieldError('userName');
        const passwordError = isFieldTouched('password') && getFieldError('password');
        return (
          <Form layout="inline" onSubmit={this.handleSubmit}>
            <FormItem
              validateStatus={userNameError ? 'error' : ''}
              help={userNameError || ''}
            >
              {getFieldDecorator('userName', {
                rules: [{ required: true, message: 'Please input your username!' }],
              })(
                <Input prefix={<Icon type="user" style={{ fontSize: 13 }} />} placeholder="Username" />
              )}
            </FormItem>
            <FormItem
              validateStatus={passwordError ? 'error' : ''}
              help={passwordError || ''}
            >
              {getFieldDecorator('password', {
                rules: [{ required: true, message: 'Please input your Password!' }],
              })(
                <Input prefix={<Icon type="lock" style={{ fontSize: 13 }} />} type="password" placeholder="Password" />
              )}
            </FormItem>
            <FormItem>
              <Button
                type="primary"
                htmlType="submit"
                disabled={hasErrors(getFieldsError())}
              >
                Log in
              </Button>
            </FormItem>
          </Form>
        );
      }
    }
    
    const WrappedHorizontalLoginForm = Form.create()(HorizontalLoginForm);
    
    ReactDOM.render(<WrappedHorizontalLoginForm />, mountNode);
    

    代码看的是真心累,各种方法属性以及html混合在一起,第一眼就不想看了。

    思考:有没有方便简单的方式来定义一个表单,像下面这样的:

    {
        "userName":{
            required:true,
            type:"string",
            message:{
              required:"Please input your username!"
            }
        },
        "password":{
            required:true,
            type:"string",
            message:{
              required:"Please input your Password!"
            }
        }
    }
    

    在公共代码库中找了下,还真有类似的类库, react-jsonschema-form;这个库只需要提供2份配置即可生成出界面,一份是json schema,一份是ui schema。真是便利的表单,配置即代码。

    下面来看下简单的配置:

    {
      "title": "A registration form",
      "description": "A simple form example.",
      "type": "object",
      "required": [
        "firstName",
        "lastName"
      ],
      "properties": {
        "firstName": {
          "type": "string",
          "title": "First name"
        },
        "lastName": {
          "type": "string",
          "title": "Last name"
        },
        "age": {
          "type": "integer",
          "title": "Age"
        },
        "bio": {
          "type": "string",
          "title": "Bio"
        },
        "password": {
          "type": "string",
          "title": "Password",
          "minLength": 3
        },
        "telephone": {
          "type": "string",
          "title": "Telephone",
          "minLength": 10
        }
      }
    }
    
    {
      "firstName": {
        "ui:autofocus": true,
        "ui:emptyValue": ""
      },
      "age": {
        "ui:widget": "updown",
        "ui:title": "Age of person",
        "ui:description": "(earthian year)"
      },
      "bio": {
        "ui:widget": "textarea"
      },
      "password": {
        "ui:widget": "password",
        "ui:help": "Hint: Make it strong!"
      },
      "date": {
        "ui:widget": "alt-datetime"
      },
      "telephone": {
        "ui:options": {
          "inputType": "tel"
        }
      }
    }
    

    json schema可以放在公共服务器,后端也可以使用同样的json schema来验证数据的合法性,同样的验证方式,同样的错误消息,真实简单实用。

    但是很快问题就来了:

    1. 当表单的布局很复杂的时候怎么办;比如firstName和lastName一行,使用一个fieldSet来包裹,其他使用默认的配置生成表单。
    2. 当需要扩展功能的时候,比如我需要一个显示/隐藏的功能;当firstName和lastName都填写之后才显示其他字段等等。
    3. 当我一些动态数据的需求的时候,比如select的数据是从接口获取并填充到组件的;又或者隐藏/显示数组的子项等等。

    基于上面的问题,怎么解决呢?

    json schema的定义:

    {
      "definitions": {
        "address": {
          "type": "object",
          "properties": {
            "street_address": {
              "type": "string"
            },
            "city": {
              "type": "string"
            },
            "state": {
              "type": "string"
            }
          },
          "required": [
            "street_address",
            "city",
            "state"
          ]
        },
        "node": {
          "type": "object",
          "properties": {
            "name": {
              "type": "string"
            },
            "children": {
              "type": "array",
              "items": {
                "$ref": "#/definitions/node"
              }
            }
          }
        }
      },
      "type": "object",
      "properties": {
        "billing_address": {
          "title": "Billing address",
          "$ref": "#/definitions/address"
        },
        "shipping_address": {
          "title": "Shipping address",
          "$ref": "#/definitions/address"
        },
        "tree": {
          "title": "Recursive references",
          "$ref": "#/definitions/node"
        }
      }
    }
    

    ui schema的定义

    {
      "ui:order": [
        "shipping_address",
        "billing_address",
        "tree"
      ]
    }
    
    【shipping_address】字段的生成结果

    首先让我们来看一看表单中的每一个项由什么组成。

    • 首先这里定义了一个fieldset,显示为Shipping address
    • 其次这里的数据结构为:Object -> [string,string,string],对应的表单显示为:ObjectField-> [ FieldTemplate->BaseInput, FieldTemplate->BaseInput, FieldTemplate->BaseInput ];
    react的组件树

    有没有可能定义出ObjectField-> RowTemplate->[ ColTemplate->FormItemTemplate->BaseInput, ColTemplate->FormItemTemplate->BaseInput, ColTemplate->FormItemTemplate->BaseInput ]这样的结构;这里要定义多模板,只能自定义Field来满足需求,但是模板不能够复用,很蛋疼。当然还有很多问题需要解决,比如ColTemplate中的span、pull和push如何来定义等。

    针对以上的问题,我们来修改一下结构。

    修改后的表单结构

    fx-schema-form

    相关文章

      网友评论

        本文标题:React JSON Schema Form

        本文链接:https://www.haomeiwen.com/subject/ujqxattx.html