antd表单、表格、请求的整体封装

1.form 表单的请求

组件代码: 

import React from "react";
import {Select,Form,Radio,Checkbox,Button,Input,DatePicker} from "antd";
import OptionList from "./../config";
import './index.less';


import moment from "moment"
import 'moment/locale/zh-cn';
moment.locale('zh-cn');
const FormItem = Form.Item;
const Option = Select.Option;
const {RangePicker} = DatePicker;
class BaseForm extends React.Component{


    commit = ()=>{
        const {getFieldsValue}=this.props.form;

        let date1=getFieldsValue();
         date1.isStart =  date1.isStart["_i"]; // 把向后段传值的moment的对象改为其_i属性;


        this.props.formSubmit(date1);//最终 向后端输出;


    };
    reset=()=>{
        //form 表单的固定方法
       this.props.form.resetFields();
    };

    initFormList = ()=>{

        const {getFieldDecorator}=this.props.form;
        const formList = this.props.formList;
        let formItemList=[];


       if(formList&&formList.length>0){
           formList.map((item,index)=>{

               let initialValue = item.initialValue||"";  // 默认为空
               let lable = item.lable;           //标题
               let placeholder = item.placeholder;  //placeholder
               let width = item.width;   //width
               let list = item.list||[];    //option
               let field= item.field;   // 字段key

               if(item.type==="input"){
                   const input=<FormItem label={lable} key={field}>
                       { getFieldDecorator(field,{initialValue:initialValue})(
                           <Input placeholder={placeholder} />
                       )}
                   </FormItem>
                   formItemList.push(input);
               }
               else if(item.type==="select"){
                   const select = <FormItem label={lable} key={field} >
                       {getFieldDecorator(field,{
                           initialValue:initialValue
                           }
                       )(
                           <Select style={{width:width}} placeholder={placeholder}>
                              {OptionList.OptionList(list)}
                           </Select>
                       )}
                   </FormItem>;
                   formItemList.push(select);
               }else if(item.type==="checkbox"){
                   const checkbox=<FormItem  label={lable} key={field}>
                       {getFieldDecorator(field,{
                           valuePropName:"checked",
                           initialValue:initialValue,
                       })(
                           <Checkbox>{lable}</Checkbox>
                       )}

                   </FormItem>
                   formItemList.push(checkbox);
               }else if(item.type==="date"){
                    const dateComponent=<FormItem label={lable} key={field} >
                        {getFieldDecorator(field,{
                             initialValue:moment(initialValue, 'YYYY/MM/DD')

                        })(
                            <DatePicker
                                showTime
                                for-mat="YY-MM-DD HH:mm:ss"
                                placeholder={placeholder}
                            />
                        )}

                    </FormItem>
                   formItemList.push(dateComponent);

               }
           })

       }

     return formItemList;
    };


    render(){

        return(<Form layout="inline">
            {this.initFormList()}
            <FormItem>
                <Button type="primary"
                onClick={()=>{this.commit()}}
                >
                  查询
                </Button>

                <Button onClick={()=>{this.reset()}}>
                  重置
                </Button>


            </FormItem>

        </Form>)
    }

}

export default  Form.create()(BaseForm);

工具函数: 输出 需要循环  得到的 子项 比如select ->option

import React from "react";

import {Select} from "antd";

const Option = Select.Option;

export default {
    OptionList :(data)=>{
          if(!data){
              return [];
          }
        let OptionMap = [<Option value="0" key="all_key">全部</Option>];
          data.map((item,index)=>{
              OptionMap.push(<Option value={item.id} key={item.id}>{item.name}</Option>)
          })
         return OptionMap;
    }
}

使用组件:

const formList= [
            {
                type: "select",
                lable: "机型",
                initialValue: "1",
                placeholder: "请选择您的机型",
                width: "200px",
                field:"iphone",
                list: [{id:"1",name:"IphoneX"}, {id:"2",name:"Ihonexs"},{id:"3",name:"IhoneXsMax"}]
            },
            {
                type: "input",
                lable: "备注",
                initialValue: "oncare",
                placeholder: "请填写你的备注",
                width: "200px",
                field:"text",

            },
            {
                type: "checkbox",
                lable: "isCare",
                initialValue: true,
                placeholder: "请填写你的备注",
                width: "200px",
                field:"isCare",

            },
            {
                type: "date",
                lable: "查询时间从",
                initialValue: "2018-09-09 02:02:02",
                placeholder: "请填写你的时间",
                width: "200px",
                field:"isStart",

            },
        ]
  <BashForm formList={formList}  formSubmit={this.submitForm}/>
import BashForm from "./../../../base/baseForm/index";

2,axios 请求封装  会 配合 上面的 form  以及下面的 table 来封装

主代码

import axios from "axios";

import {Modal} from "antd";
import paginationUtil from "./util";



const axiosList = (url,data,obj)=>{
   // console.log(data)
    const _this=obj;
    const params = data||null;
    axiosUtil({url,params}).then((res)=>{
        if(res){
         //   console.log(res.list)
            _this.setState({
                dataSource:res.list,
                pagination:paginationUtil.pagination(res,(current)=>{
                    _this.setState({current});
               setTimeout(()=>{_this.request({...params,...{page:_this.state.current}})},0)  //this.setState 所以需要 settimeout 放到异步队列
                })
            })
        }
    });


};


const  axiosUtil = function ({...option}) {

  //  console.log(option.params)
    //在路由部分插入加载动画 移动端可以直接使用 Toast组件
    let loading =document.getElementById("loadingBox");
    axios.interceptors.request.use(function (config) {
        loading.style.display="block";
        return config
    });

//拦截响应
    axios.interceptors.response.use(function (config) {

        loading.style.display="none";
        return config
    });
    return new Promise((resolve,reject)=>{
        axios({
            url:option.url,
            method:option.method||"post",
            baseURL:"https://www.easy-mock.com/mock/5bb61edebaa7dc5e5e8d18d0/mockapi",
            timeout:4000,
            params:option.params?option.params:""
        }).then((res)=>{

           if(res.status=="200"){
                 //直接拿结果 提高效率
                if(res.data.code=="0"){
                    resolve(res.data.result);
                }else{
                    // 直接抛出报错信息 方便调试
                    Modal.info({
                        title:`接口提示`,
                        content:`错误码: ${res.data.code},错误信息:${res.data.msg}`
                    })
                }

           }else{
               reject(res);
           }
        })


    })


};

export default {axiosUtil,axiosList};

应用 :

request(paramsObj){
       axios.axiosList("/table/basic",paramsObj,this)

     }

    componentDidMount(){
      this.request();
    }

//搜索页码归1
 submitForm=(params)=>{
        this.request({...params,...{page:1}});
    };

3, table的封装

主代码 :

import React from "react";
import {Table} from "antd";
import './index.less';

class Itable extends React.Component{
  //
    onRowClick(item,index){
        let  selectedRowKeys = this.props.selecekeys;
        let  selectedRows = this.props.that.state.selectedRows;
        if(this.props.rowSelection==="checkbox"){
                if(this.props.selecekeys.indexOf(index+1)===-1){
                    selectedRowKeys.push(index+1);
                    selectedRows.push(item);
                    this.props.that.setState({selectedRowKeys,selectedRows});
                }else{
                   const index_=this.props.selecekeys.indexOf(index+1);
                    selectedRowKeys.splice(index_,1);
                    selectedRows.splice(index_,1);
                    this.props.that.setState({selectedRowKeys,selectedRows});
                }
        }else if(this.props.rowSelection==="radio"||this.props.rowSelection===""){
            this.props.that.setState({selectedRowKeys:index,selectedRows:item});
        }
    }


    updateSelectedItem(selectedRowKeys,selectedItem){
        this.setState({
            selectedRowKeys,
            selectedItem
        })
    }
    tableIntit(){
       // console.log(this.props)

        let rowSelection ={
           type: this.props.rowSelection==="checkbox"?"checkbox":"radio",
           selectedRowKeys:this.props.selecekeys,
           onChange:this.updateSelectedItem.bind(this.props.that)
       };
    return   <Table

        columns={this.props.columns}
        dataSource={this.props.dataSource}
        bordered
        pagination={this.props.pagination}
        rowSelection={this.props.rowSelection===false?null:rowSelection}

        onRow={(item,index)=>{
            return { onClick: () => {
                              this.onRowClick(item,index);

                },       // 点击行
            }
        }}
    />

    }

   render(){
       return(
           <div>
               {this.tableIntit()}
           </div>
       )
   }
}
export default Itable

使用: 

 constructor(props,context){
        super(props,context);
        this.state={
            dataSource:[],
            selectedRows:[],
            selectedRowKeys:[],
            sortOrder:"",
            pagination:{},
            current:1,
            isShow:false,
            params:{}
        };
    }


 const columns = [
                            {
                              title:"id",
                              dataIndex:"id",
                                width:80,
                            },{
                                title:"名字",
                                dataIndex:"name",
                              width:80
                            },{
                                title:"年龄",
                                dataIndex:"age",
                                width:80,
                               sorter:(a,b)=>{
                                    return a.age-b.age;
                               },

                              sortOrder:this.state.sortOrder,

                            },{
                                title:"地址",
                                dataIndex:"address",
                                width:80
                            },{
                                title:"其他",
                                dataIndex:"other",
                                width:80,

                            },


                ];


              <Itable
              that={this}  
             selecekeys={this.state.selectedRowKeys}
             rowSelection="checkbox"
             columns={columns}
             dataSource={this.state.dataSource}
             pagination={this.state.pagination}
                />

import Itable from "./../../../base/baseTable/index";

 

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值