極客react之Ant Design Pro系列快速入門(四)--界面新增

新增界面

  1. src/routes文件下新建目錄NewPage,進入該目錄添加文件
  2. 新建界面樣式NewPage.less
    @import "~antd/lib/style/themes/default.less";

     

  3. 新建頁面文件NewPage.js
    import React, { PureComponent, Fragment } from 'react';
    import { connect } from 'dva';
    import moment from 'moment';
    import {
      Row,
      Col,
      Card,
      Form,
      Input,
      Select,
      Icon,
      Button,
      Dropdown,
      Menu,
      InputNumber,
      DatePicker,
      Modal,
      message,
      Badge,
      Divider,
    } from 'antd';
    import StandardTable from 'components/StandardTable';
    import PageHeaderLayout from '../../layouts/PageHeaderLayout';
    
    import styles from './NewPage.less';
    
    const FormItem = Form.Item;
    const { Option } = Select;
    const getValue = obj =>
      Object.keys(obj)
        .map(key => obj[key])
        .join(',');
    const statusMap = ['default', 'processing', 'success', 'error'];
    const status = ['關閉', '運行中', '已上線', '異常'];
    
    const CreateForm = Form.create()(props => {
      const { modalVisible, form, handleAdd, handleModalVisible } = props;
      const okHandle = () => {
        form.validateFields((err, fieldsValue) => {
          if (err) return;
          form.resetFields();
          handleAdd(fieldsValue);
        });
      };
      return (
        <Modal
          title="新建規則"
          visible={modalVisible}
          onOk={okHandle}
          onCancel={() => handleModalVisible()}
        >
          <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="描述">
            {form.getFieldDecorator('desc', {
              rules: [{ required: true, message: 'Please input some description...' }],
            })(<Input placeholder="請輸入" />)}
          </FormItem>
        </Modal>
      );
    });
    
    @connect(({ rule, loading }) => ({
      rule,
      loading: loading.models.rule,
    }))
    @Form.create()
    export default class NewPage extends PureComponent {
      state = {
        modalVisible: false,
        expandForm: false,
        selectedRows: [],
        formValues: {},
      };
    
      componentDidMount() {
        const { dispatch } = this.props;
        dispatch({
          type: 'rule/fetch',
        });
      }
    
      handleStandardTableChange = (pagination, filtersArg, sorter) => {
        const { dispatch } = this.props;
        const { formValues } = this.state;
    
        const filters = Object.keys(filtersArg).reduce((obj, key) => {
          const newObj = { ...obj };
          newObj[key] = getValue(filtersArg[key]);
          return newObj;
        }, {});
    
        const params = {
          currentPage: pagination.current,
          pageSize: pagination.pageSize,
          ...formValues,
          ...filters,
        };
        if (sorter.field) {
          params.sorter = `${sorter.field}_${sorter.order}`;
        }
    
        dispatch({
          type: 'rule/fetch',
          payload: params,
        });
      };
    
      handleFormReset = () => {
        const { form, dispatch } = this.props;
        form.resetFields();
        this.setState({
          formValues: {},
        });
        dispatch({
          type: 'rule/fetch',
          payload: {},
        });
      };
    
      toggleForm = () => {
        const { expandForm } = this.state;
        this.setState({
          expandForm: !expandForm,
        });
      };
    
      handleMenuClick = e => {
        const { dispatch } = this.props;
        const { selectedRows } = this.state;
    
        if (!selectedRows) return;
    
        switch (e.key) {
          case 'remove':
            dispatch({
              type: 'rule/remove',
              payload: {
                no: selectedRows.map(row => row.no).join(','),
              },
              callback: () => {
                this.setState({
                  selectedRows: [],
                });
              },
            });
            break;
          default:
            break;
        }
      };
    
      handleSelectRows = rows => {
        this.setState({
          selectedRows: rows,
        });
      };
    
      handleSearch = e => {
        e.preventDefault();
    
        const { dispatch, form } = this.props;
    
        form.validateFields((err, fieldsValue) => {
          if (err) return;
    
          const values = {
            ...fieldsValue,
            updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf(),
          };
    
          this.setState({
            formValues: values,
          });
    
          dispatch({
            type: 'rule/fetch',
            payload: values,
          });
        });
      };
    
      handleModalVisible = flag => {
        this.setState({
          modalVisible: !!flag,
        });
      };
    
      handleAdd = fields => {
        const { dispatch } = this.props;
        dispatch({
          type: 'rule/add',
          payload: {
            description: fields.desc,
          },
        });
    
        message.success('添加成功');
        this.setState({
          modalVisible: false,
        });
      };
    
      render() {
        const { form } = this.props;
        const { getFieldDecorator } = form;
        const {
          rule: { data },
          loading,
        } = this.props;
        const { selectedRows, modalVisible } = this.state;
    
        const columns = [
          {
            title: '規則編號',
            dataIndex: 'no',
          },
          {
            title: '描述',
            dataIndex: 'description',
          },
          {
            title: '服務調用次數',
            dataIndex: 'callNo',
            sorter: true,
            align: 'right',
            render: val => `${val} 萬`,
            // mark to display a total number
            needTotal: true,
          },
          {
            title: '狀態',
            dataIndex: 'status',
            filters: [
              {
                text: status[0],
                value: 0,
              },
              {
                text: status[1],
                value: 1,
              },
              {
                text: status[2],
                value: 2,
              },
              {
                text: status[3],
                value: 3,
              },
            ],
            onFilter: (value, record) => record.status.toString() === value,
            render(val) {
              return <Badge status={statusMap[val]} text={status[val]} />;
            },
          },
          {
            title: '更新時間',
            dataIndex: 'updatedAt',
            sorter: true,
            render: val => <span>{moment(val).format('YYYY-MM-DD HH:mm:ss')}</span>,
          },
          {
            title: '操作',
            render: () => (
              <Fragment>
                <a href="">配置</a>
                <Divider type="vertical" />
                <a href="">訂閱警報</a>
              </Fragment>
            ),
          },
        ];
    
        const menu = (
          <Menu onClick={this.handleMenuClick} selectedKeys={[]}>
            <Menu.Item key="remove">刪除</Menu.Item>
            <Menu.Item key="approval">批量審批</Menu.Item>
          </Menu>
        );
    
        const parentMethods = {
          handleAdd: this.handleAdd,
          handleModalVisible: this.handleModalVisible,
        };
    
        return (
          <PageHeaderLayout title="自定義功能">
            <Card bordered={false}>
              <div className={styles.tableList}>
                <div className={styles.tableListForm}>
                
          <Form onSubmit={this.handleSearch} layout="inline">
            <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
              <Col md={8} sm={24}>
                <FormItem label="規則編號">
                  {getFieldDecorator('no')(<Input placeholder="請輸入" />)}
                </FormItem>
              </Col>
              <Col md={8} sm={24}>
                <FormItem label="使用狀態">
                  {getFieldDecorator('status')(
                    <Select placeholder="請選擇" style={{ width: '100%' }}>
                      <Option value="0">關閉</Option>
                      <Option value="1">運行中</Option>
                    </Select>
                  )}
                </FormItem>
              </Col>
              <Col md={8} sm={24}>
                <FormItem label="調用次數">
                  {getFieldDecorator('number')(<InputNumber style={{ width: '100%' }} />)}
                </FormItem>
              </Col>
            </Row>
            <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
              <Col md={8} sm={24}>
                <FormItem label="更新日期">
                  {getFieldDecorator('date')(
                    <DatePicker style={{ width: '100%' }} placeholder="請輸入更新日期" />
                  )}
                </FormItem>
              </Col>
    
            </Row>
            <div style={{ overflow: 'hidden' }}>
              <div style={{ float: 'right', marginBottom: 24 }}>
                <Button type="primary" htmlType="submit">
                  查詢
                </Button>
                <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
                  重置
                </Button>
              </div>
            </div>
          </Form>
                </div>
                <div className={styles.tableListOperator}>
                  <Button icon="plus" type="primary" onClick={() => this.handleModalVisible(true)}>
                    新建
                  </Button>
                  {selectedRows.length > 0 && (
                    <span>
                      <Button>批量操作</Button>
                      <Dropdown overlay={menu}>
                        <Button>
                          更多操作 <Icon type="down" />
                        </Button>
                      </Dropdown>
                    </span>
                  )}
                </div>
                <StandardTable
                  selectedRows={selectedRows}
                  loading={loading}
                  data={data}
                  columns={columns}
                  onSelectRow={this.handleSelectRows}
                  onChange={this.handleStandardTableChange}
                />
              </div>
            </Card>
            <CreateForm {...parentMethods} modalVisible={modalVisible} />
          </PageHeaderLayout>
        );
      }
    }
    
     
  4. 聲明路徑動態加載新建界面app/src/common/route.js
    '/new/newpage': {
       component: dynamicWrapper(app, [], () =>
         import('../routes/New/NewPage')
       ),
     },

     

  5. 菜單顯示該功能 app/src/commom.menu.js
    {
         name: '自定義模塊',
         icon: 'form',
         path: 'new',
         children: [
         {
             name: '新功能',
             path: 'newpage',
         },
         ],
     },

     

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章