index.js 2.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
import React, { Component } from 'react';
import _ from 'lodash';
import { Table, Button, Form } from 'antd';

class TableInput extends Component {

  constructor(props, context) {
    super(props, context);
    this.onAdd = this::this.onAdd;
    this.onOk = this::this.onOk;
    this.state = {
      editing: false,
      operation: 'none',
    };
  }

  onAdd() {
    this.setState({
      editing: true,
      operation: 'add',
    });
  }
  onOk() {
    const { value, items, form, onChange } = this.props;
    const row = {};
    _.castArray(items).forEach((item) => {
      row[item.name] = form.getFieldValue(item.name);
    });
    if (this.state.operation === 'add') {
      (onChange || _.noop)([...(value || []), row]);
    }
    this.setState({
      editing: false,
      operation: 'none',
    });
  }
  makeColumns() {
    const { items } = this.props;
    return _.castArray(items)
      .map((item) => {
        return {
          ...item,
          title: item.label,
          key: item.name,
          dataIndex: item.name,
        };
      });
  }
  makeDataSource() {
    const { value } = this.props;
    return _.castArray(value || [])
      .map((row, idx) => ({
        ...row,
        __key__: idx,
      }));
  }

  render() {
    const { items, form, children } = this.props;
    if (this.state.editing) {
      const fields = _.castArray(children)
        .map((child, i) => {
          const item = items[i];
          return (
            <Form.Item {...item}>
              {
                form.getFieldDecorator(item.name, item)(
                  child,
                )
              }
            </Form.Item>
          );
        },
        this,
      );
      return (
        <div>
          {[
            ...fields,
            <Button onClick={this.onOk}>确定</Button>,
          ]}
        </div>
      );
    } else {
      return (
        <div>
          <Button onClick={this.onAdd}>新增</Button>
          <Table rowKey="__key__" dataSource={this.makeDataSource()} columns={this.makeColumns()} />
        </div>
      );
    }
  }
}

export default Form.create()(TableInput);