封装表单模块

后台管理系统经常用到表单查询,因此做了个封装

myorder.js

import React from ‘react‘;
import { Card, Button, Table, Form, Select, Modal, DatePicker, message} from ‘antd‘
import axios from ‘./axios‘
import Utils from ‘./utils‘
import BaseForm from ‘./BaseForm‘
const FormItem = Form.Item;
const Option = Select.Option;
export default class MyOrder extends React.Component{
    state  = {
        orderInfo:{},
        orderConfirmVisble:false
    }
    params = {
        page: 1
    }
    formList = [
        {
            type:‘SELECT‘,
            label:‘城市‘,
            field:‘city‘,
            placeholder:‘全部‘,
            initialValue:‘1‘,
            width:80,
            list: [{ id: ‘0‘, name: ‘全部‘ }, { id: ‘1‘, name: ‘北京‘ }, { id: ‘2‘, name: ‘天津‘ }, { id: ‘3‘, name: ‘上海‘ }]
        },
        {
            type: ‘时间查询‘
        },
        {
            type: ‘SELECT‘,
            label: ‘订单状态‘,
            field:‘order_status‘,
            placeholder: ‘全部‘,
            initialValue: ‘1‘,
            width: 80,
            list: [{ id: ‘0‘, name: ‘全部‘ }, { id: ‘1‘, name: ‘进行中‘ }, { id: ‘2‘, name: ‘结束行程‘ }]
        }
    ]
    componentDidMount(){
        this.requestList()
    }

    handleFilter = (params)=>{
        this.params = params;
        this.requestList();
    }
    requestList = ()=>{
        let _this = this;
        axios.ajax({
            url:‘/order/list‘,
            data:{
                params: this.params
            }
        }).then((res)=>{
            let list = res.result.item_list.map((item, index) => {
                item.key = index;
                return item;
            });
            this.setState({
                list,
                pagination: Utils.pagination(res, (current) => {
                    _this.params.page = current;
                    _this.requestList();
                })
            },function(){
                console.log(this.state.pagination)
            })
        })
    }
    // 订单结束确认
    handleConfirm = ()=>{
        let item = this.state.selectedItem;
        if (!item) {
            Modal.info({
                title: ‘信息‘,
                content: ‘请选择一条订单进行结束‘
            })
            return;
        }
        axios.ajax({
            url:‘/order/ebike_info‘,
            data:{
                params:{
                    orderId: item.id
                }
            }
        }).then((res)=>{
            if(res.code ==0 ){
                this.setState({
                    orderInfo:res.result,
                    orderConfirmVisble: true
                })
            }
        })
    }

    // 结束订单
    handleFinishOrder = ()=>{
        let item = this.state.selectedItem;
        axios.ajax({
            url: ‘/order/finish_order‘,
            data: {
                params: {
                    orderId: item.id
                }
            }
        }).then((res) => {
            if (res.code == 0) {
                message.success(‘订单结束成功‘)
                this.setState({
                    orderConfirmVisble: false
                })
                this.requestList();
            }
        })
    }
    onRowClick = (record, index) => {

        let selectKey = [index];
        this.setState({
            selectedRowKeys: selectKey,
            selectedItem: record
        })
    }

    openOrderDetail = ()=>{
        let item = this.state.selectedItem;
        if (!item) {
            Modal.info({
                title: ‘信息‘,
                content: ‘请先选择一条订单‘
            })
            return;
        }
        window.open(`/#/common/order/detail/${item.id}`,‘_blank‘)
    }
    render(){
        const columns = [
            {
                title:‘订单编号‘,
                dataIndex:‘order_sn‘
            },
            {
                title: ‘车辆编号‘,
                dataIndex: ‘bike_sn‘
            },
            {
                title: ‘用户名‘,
                dataIndex: ‘user_name‘
            },
            {
                title: ‘手机号‘,
                dataIndex: ‘mobile‘
            },
            {
                title: ‘里程‘,
                dataIndex: ‘distance‘,
                render(distance){
                    return distance/1000 + ‘Km‘;
                }
            },
            {
                title: ‘行驶时长‘,
                dataIndex: ‘total_time‘
            },
            {
                title: ‘状态‘,
                dataIndex: ‘status‘
            },
            {
                title: ‘开始时间‘,
                dataIndex: ‘start_time‘
            },
            {
                title: ‘结束时间‘,
                dataIndex: ‘end_time‘
            },
            {
                title: ‘订单金额‘,
                dataIndex: ‘total_fee‘
            },
            {
                title: ‘实付金额‘,
                dataIndex: ‘user_pay‘
            }
        ]
        const formItemLayout = {
            labelCol:{span:5},
            wrapperCol:{span:19}
        }
        const selectedRowKeys = this.state.selectedRowKeys;
        const rowSelection = {
            type: ‘radio‘,
            selectedRowKeys
        }
        return (
            <div>
                <Card>
                    <BaseForm formList={this.formList} filterSubmit={this.handleFilter}/>
                </Card>
                <Card style={{marginTop:10}}>
                    <Button type="primary" onClick={this.openOrderDetail}>订单详情</Button>
                    <Button type="primary" style={{marginLeft:10}} onClick={this.handleConfirm}>结束订单</Button>
                </Card>
                <div className="content-wrap">
                    <Table
                        bordered
                        columns={columns}
                        dataSource={this.state.list}
                        pagination={this.state.pagination}
                        rowSelection={rowSelection}
                        onRow={(record, index) => {
                            return {
                                onClick: () => {
                                    this.onRowClick(record, index);
                                }
                            };
                        }}
                    />
                </div>
                <Modal
                    title="结束订单"
                    visible={this.state.orderConfirmVisble}
                    onCancel={()=>{
                        this.setState({
                            orderConfirmVisble:false
                        })
                    }}
                    onOk={this.handleFinishOrder}
                    width={600}
                >
                    <Form layout="horizontal">
                        <FormItem label="车辆编号" {...formItemLayout}>
                            {this.state.orderInfo.bike_sn}
                        </FormItem>
                        <FormItem label="剩余电量" {...formItemLayout}>
                            {this.state.orderInfo.battery + ‘%‘}
                        </FormItem>
                        <FormItem label="行程开始时间" {...formItemLayout}>
                            {this.state.orderInfo.start_time}
                        </FormItem>
                        <FormItem label="当前位置" {...formItemLayout}>
                            {this.state.orderInfo.location}
                        </FormItem>
                    </Form>
                </Modal>
            </div>
        );
    }
}

utils.js

import React from ‘react‘;
import { Select } from ‘antd‘
const Option = Select.Option;
export default {
    pagination(data,callback){
        console.log("data",data);
        return {
            onChange:(current)=>{
                callback(current)
            },
            current:data.result.page,
            pageSize:data.result.page_size,
            total: data.result.total_count,
            showTotal:()=>{
                return `共${data.result.total_count}条`
            },
            showQuickJumper:true
        }
    },
    getOptionList(data){
        if(!data){
            return [];
        }
        let options = [] //[<Option value="0" key="all_key">全部</Option>];
        data.map((item)=>{
            options.push(<Option value={item.id} key={item.id}>{item.name}</Option>)
        })
        return options;
    }
}

axios.js

import JsonP from ‘jsonp‘
import axios from ‘axios‘
import { Modal } from ‘antd‘
export default class Axios {

    static ajax(options){
        let loading;
        if (options.data && options.data.isShowLoading !== false){
            loading = document.getElementById(‘ajaxLoading‘);
            loading.style.display = ‘block‘;
        }
        let baseApi = ‘https://www.easy-mock.com/mock/5a7278e28d0c633b9c4adbd7/api‘;
        return new Promise((resolve,reject)=>{
            axios({
                url:options.url,
                method:‘get‘,
                baseURL:baseApi,
                timeout:5000,
                params: (options.data && options.data.params) || ‘‘
            }).then((response)=>{
                if (options.data && options.data.isShowLoading !== false) {
                    loading = document.getElementById(‘ajaxLoading‘);
                    loading.style.display = ‘none‘;
                }
                if (response.status == ‘200‘){
                    let res = response.data;
                    if (res.code == ‘0‘){
                        resolve(res);
                    }else{
                        Modal.info({
                            title:"提示",
                            content:res.msg
                        })
                    }
                }else{
                    reject(response.data);
                }
            })
        });
    }
}

BaseForm.js

import React from ‘react‘
import { Input, Select, Form, Button, Checkbox, Radio, DatePicker} from ‘antd‘
import Utils from ‘./utils‘;
const FormItem = Form.Item;
const Option = Select.Option;

class FilterForm extends React.Component{

    handleFilterSubmit = ()=>{
        let fieldsValue = this.props.form.getFieldsValue();
        this.props.filterSubmit(fieldsValue);
    }

    reset = ()=>{
        this.props.form.resetFields();
    }

    initFormList = ()=>{
        const { getFieldDecorator } = this.props.form;
        const formList = this.props.formList;
        const formItemList = [];
        if (formList && formList.length>0){
            formList.forEach((item,i)=>{
                let label = item.label;
                let field = item.field;
                let initialValue = item.initialValue || ‘‘;
                let placeholder = item.placeholder;
                let width = item.width;
                if (item.type == ‘时间查询‘){
                    const begin_time = <FormItem label="订单时间" key={field}>
                        {
                            getFieldDecorator(‘begin_time‘)(
                                <DatePicker showTime={true} placeholder={placeholder} format="YYYY-MM-DD HH:mm:ss"/>
                            )
                        }
                    </FormItem>;
                    formItemList.push(begin_time)
                    const end_time = <FormItem label="~" colon={false} key={field}>
                        {
                            getFieldDecorator(‘end_time‘)(
                                <DatePicker showTime={true} placeholder={placeholder} format="YYYY-MM-DD HH:mm:ss" />
                            )
                        }
                    </FormItem>;
                    formItemList.push(end_time)
                }else if(item.type == ‘INPUT‘){
                    const INPUT = <FormItem label={label} key={field}>
                        {
                            getFieldDecorator([field],{
                                initialValue: initialValue
                            })(
                                <Input type="text" placeholder={placeholder} />
                            )
                        }
                    </FormItem>;
                    formItemList.push(INPUT)
                } else if (item.type == ‘SELECT‘) {
                    const SELECT = <FormItem label={label} key={field}>
                        {
                            getFieldDecorator([field], {
                                initialValue: initialValue
                            })(
                                <Select
                                    style={{ width: width }}
                                    placeholder={placeholder}
                                >
                                    {Utils.getOptionList(item.list)}
                                </Select>
                            )
                        }
                    </FormItem>;
                    formItemList.push(SELECT)
                } else if (item.type == ‘CHECKBOX‘) {
                    const CHECKBOX = <FormItem label={label} key={field}>
                        {
                            getFieldDecorator([field], {
                                valuePropName: ‘checked‘,
                                initialValue: initialValue //true | false
                            })(
                                <Checkbox>
                                    {label}
                                </Checkbox>
                            )
                        }
                    </FormItem>;
                    formItemList.push(CHECKBOX)
                }
            })
        }
        return formItemList;
    }
    render(){
        return (
            <Form layout="inline">
                { this.initFormList() }
                <FormItem>
                    <Button type="primary" style={{ margin: ‘0 20px‘ }} onClick={this.handleFilterSubmit}>查询</Button>
                    <Button onClick={this.reset}>重置</Button>
                </FormItem>
            </Form>
        );
    }
}
export default Form.create({})(FilterForm);

效果

原文地址:https://www.cnblogs.com/mosquito18/p/9786209.html

时间: 2024-10-05 05:50:09

封装表单模块的相关文章

httpclient模拟post请求json封装表单数据

1 public static String httpPostWithJSON(String url) throws Exception { 2 3 HttpPost httpPost = new HttpPost(url); 4 CloseableHttpClient client = HttpClients.createDefault(); 5 String respContent = null; 6 7 // json方式 8 JSONObject jsonParam = new JSON

封装表单自定义错误信息。(阻止默认错误信息提示,添加自定义错误信息提示)

1 前台提交信息到后台,两种表单验证: 2 1,form 表单验证 3 2,ajax 无刷新页面提交 4 5 表单验证方法一般有: 6 1,浏览器端验证 7 2,服务器端验证 8 3,ajax验证 9 4,浏览器和服务器双重验证 10 11 html5表单新增类型: 12 email,url,number,range,data(date,month,week,time,datetime,datetime-local),search,color,tel等 13 ======== 14 重点:pat

封装表单案例

将页面的数据封装到表单中 register.jsp <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+

.Net Core使用视图组件(ViewComponent)封装表单文本框控件

实例程序的界面效果如下图所示: 在表单中的搜索条件有姓名,学号,成绩.他们在一行中按照水平三等分排列. 在cshtml中用html实现上述表单效果的的代码如下: 1 <form class="form-horizontal" role="form"> 2 <div class="row"> 3 <div class="form-group col-md-4"> 4 <label for

vue+elementui 封装表单验证

其实很简单:步骤1:先用element 把页面写出来:步骤2.规则验证,需要自定义验证的,引入对应的自定义验证方法, 3.封装一个自定义验证的js. 1.先把结构写出来: 注意: from 表单上有model(绑定数据),ref(提交的时有用),rules(对表单的验证规则),这三者缺一不可. 2.代码: <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width

request对象封装表单数据

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // test1(request); // test2(request); test3(request); } //获取单个控件的值 public void test1(HttpServletRequest request){ String name = request

dom 封装表单控件

<!doctype html> <html> <head> <meta charset="utf-8"> <title>无标题文档</title> <style> body { margin: 0; padding: 0; font-family: '微软雅黑'; } form { border: 1px solid #eee; border-radius: 10px; width: 600px; ma

通过反射自动封装表单字段

package cn.jbit.util; import java.beans.IntrospectionException; import java.beans.PropertyDescriptor; import java.io.UnsupportedEncodingException; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.net.URLDecoder; import jav

Laravel 5.5 FormRequest 自定义表单请求验证类

1.把表单验证逻辑写在Controller中,这是最基础的方法,但是不好维护,如: 1 namespace App\Http\Controllers\Admin; 2 3 use Illuminate\Http\Request; 4 use App\Http\Controllers\Controller; 5 6 class MemberController extends Controller 7 { 8 // 登录模块 9 public function login (Request $re