React根據(jù)后臺數(shù)據(jù)動態(tài)生成Form表單

import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import { Form, InputNumber, Input, DatePicker, Button, Select } from 'antd';
import moment from 'moment';
// 推薦在入口文件全局設(shè)置 locale
import 'moment/locale/zh-cn';
moment.locale('zh-cn');

const FormItem = Form.Item;
const Option = Select.Option;

// 后臺返回的數(shù)據(jù)格式
const data = [
  {
    'field': 'jobid',
    'text': '工號',
    'errorMessage': '請輸入工號',
    'required': true,
    'type': 'int',
    'value': 100
  },{
    'field': 'date',
    'text': '日期',
    'errorMessage': '請輸入日期',
    'required': false,
    'type': 'date',
    'value': '2017-10-20'
  },{
    'field': 'username',
    'text': '用戶名',
    'errorMessage': '請輸入用戶名',
    'required': true,
    'type': 'char',
    'value': 'hello world'
  },{
    'field': 'customer',
    'text': '客戶',
    'errorMessage': '請輸入客戶',
    'required': true,
    'type': 'select',
    'value': '中興',
    'options': ['貝爾', '中興', '烽火']
  }
]

// formItem css 樣式
const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 6 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 14 },
  }
}

// 保存按鈕 css 樣式
const tailFormItemLayout = {
  wrapperCol: {
    xs: {
      span: 24,
      offset: 0,
    },
    sm: {
      span: 14,
      offset: 6,
    },
  }
}

// form css 樣式
const formLayout = {
  width: 400,
  marginTop: 100,
  marginLeft: 'auto',
  marginRight: 'auto'
}


class App extends Component {
  handleSubmit(e) {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (!err) {
        console.log('Received values of form: ', values);
      }
    });
  }

  /**
   * 根據(jù)后臺返回的 data 中 type 類型生成不同的組件
   * @param item  json
   * @param Component
   */
  switchItem(item) {
    const type = item.type;
    switch (type) {
      case 'int':
        return <InputNumber style={{ width: '100%' }} />;
        break;
      case 'char':
        return <Input />;
        break;
      case 'date':
        return <DatePicker style={{ width: '100%' }} />;
        break;
      case 'select':
        return (
          <Select>
          {
            item.options.map((option, index) => {
              return (<Option key={index} value={option}>{option}</Option>)
            })
          }
          </Select>
        )
      default:
        return <Input />;
        break;
    }
  }

  render() {
    const { getFieldDecorator } = this.props.form;
    return (
      <Form onSubmit={this.handleSubmit} style={formLayout}>
        {
          data.map((item, index) => {
            // type 為 date 日期格式需要強制轉(zhuǎn)化為 moment 格式
            item.value = item.type == 'date' ? moment(item.value, 'YYYY-MM-DD') : item.value;
            return (
              <FormItem
                key={index}
                {...formItemLayout}
                label={item.text}
                hasFeedback
              >
                {getFieldDecorator(item.field, {
                  initialValue: item.value,
                  rules: [{
                    required: item.required,
                    message: item.errorMessage
                  }],
                })(
                  this.switchItem(item)
                )}
              </FormItem>
            )
          })
        }
        <FormItem {...tailFormItemLayout}>
          <Button type="primary" htmlType="submit">
            保存
          </Button>
        </FormItem>
      </Form>
    )
  }
}

const AppForm = Form.create()(App);

ReactDOM.render(<AppForm />, document.getElementById('root'));

效果圖:


20170322101851197.png
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容