1. 程式人生 > >React根據後臺資料動態生成Form表單

React根據後臺資料動態生成Form表單

import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import { Form, InputNumber, Input, DatePicker, Button, Select } from 'antd';
import moment from 'moment';
// 推薦在入口檔案全域性設定 locale
import 'moment/locale/zh-cn';
moment.locale('zh-cn');

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

// 後臺返回的資料格式
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); } }); } /** * 根據後臺返回的 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 日期格式需要強制轉化為 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'));

效果圖:

效果圖