【共享單車】—— React後臺管理系統開發手記:員工管理之增刪改查

前言:如下內容基於React全家桶+AntD實戰課程的學習實踐過程記錄。最終成果github地址:https://github.com/66Web/react-antd-manager,歡迎star。javascript


 

1、建立員工表單子組件java

  • 建立員工、編輯員工、員工詳情、刪除員工共用一個Modal彈框表單
    <Modal 
          title={this.state.title}
          visible={this.state.isVisible}
          onOk={this.handleSubmit}
          onCancel={() => {
                 this.userForm.props.form.resetFields();
                 this.setState({
                      isVisible: false
                 })
          }}
          width={600}
          {...footer}
    >
         <UserForm type={this.state.type} userInfo={this.state.userInfo} wrappedComponentRef={(inst) => {this.userForm = inst;}}/>
    </Modal>  
  • 建立、編輯員工提交:共用handleSubmit(),判斷type,經過axios.ajax()調用不一樣的Easy Mock數據接口請求
    //建立編輯員工提交
    handleSubmit = () => {
            let type = this.state.types;
            let data = this.userForm.props.form.getFieldsValue();
            axios.ajax({
                url: type=='create'?'/user/add':'/user/edit',
                data: {
                    params: data
                }
            }).then((res) => {
                if(res.code === 0){
                   this.userForm.props.form.resetFields();
                   this.setState({
                       isVisible: false
                   })
                   this.requestList();
                }
            })
    }    
  • 關鍵:
  1. getFieldDecorator實現表單數據雙向綁定
    const {getFieldDecorator} = this.props.form;  
  2. 獲取this.props.userInfo:【編輯員工】中設置表單默認數據、【員工信息】中顯示員工信息
  3. 判斷this.props.type:當type == 'detail'時,直接渲染員工信息userInfo,再也不渲染Form表單
  4. 判斷this.state.type:當type == 'detail'時,不顯示Modal的footer按鈕
    let footer = {};
    if(this.state.type == 'detail'){
           footer = {
               footer: null
           }
    }  
  • 組件實現
    //子組件:建立員工表單
    class UserForm extends React.Component{
    
        getState = (state) => {
            let config = {
                '1':'鹹魚一條',
                '2':'風華浪子',
                '3':'北大才子一枚',
                '4':'百度FE',
                '5':'創業者'
            }
            return config[state];
        }
    
        render(){
            let type = this.props.type;
            let userInfo = this.props.userInfo || {};
            const {getFieldDecorator} = this.props.form;
            const formItemLayout= {
                labelCol:{span: 5},
                wrapperCol:{span: 19}
            }
            return (
                <Form layout="horizontal">
                      <FormItem label="用戶名" {...formItemLayout}>
                            {
                                type == 'detail' ? userInfo.userName :
                                getFieldDecorator('user_name',{
                                    initialValue: userInfo.userName
                                })(
                                    <Input type="text" placeholder="請輸入用戶名"/>
                                )
                            }
                      </FormItem>
                      <FormItem label="性別" {...formItemLayout}>
                            {
                                type == 'detail' ? userInfo.sex == 1 ? '男' : '女' :
                                getFieldDecorator('sex',{
                                    initialValue: userInfo.sex
                                })(
                                    <RadioGroup>
                                        <Radio value={1}>男</Radio>
                                        <Radio value={2}>女</Radio>
                                    </RadioGroup>
                                )
                            }
                      </FormItem>
                      <FormItem label="狀態" {...formItemLayout}>
                            {
                                type == 'detail' ? this.getState(userInfo.state) :
                                getFieldDecorator('state',{
                                    initialValue: userInfo.state
                                })(
                                    <Select>
                                        <Option value={1}>鹹魚一條</Option>
                                        <Option value={2}>風華浪子</Option>
                                        <Option value={3}>北大才子一枚</Option>
                                        <Option value={4}>百度FE</Option>
                                        <Option value={5}>創業者</Option>
                                    </Select>
                                )
                            }
                      </FormItem>
                      <FormItem label="生日" {...formItemLayout}>
                            {
                                type == 'detail' ? userInfo.birthday :
                                getFieldDecorator('birthday',{
                                    initialValue: moment(userInfo.birthday)
                                })(
                                    <DatePicker format="YYYY-MM-DD"/>
                                )
                            }
                      </FormItem>
                      <FormItem label="聯繫地址" {...formItemLayout}>
                            {
                                type == 'detail' ? userInfo.address :
                                getFieldDecorator('address',{
                                    initialValue: userInfo.address
                                })(
                                    <TextArea rows={3} placeholder="請輸入聯繫地址"/>
                                )
                            }
                      </FormItem>
                </Form>
            )
        }
    }
    UserForm = Form.create({})(UserForm);

      

2、功能區操做react

  •  建立員工、編輯員工、員工詳情、刪除員工共用一個功能操做函數handleOperate()
    <Card style={{marginTop:10}} className="operate-wrap">
              <Button type="primary" icon="plus" onClick={() => this.handleOperate('create')}>建立員工</Button>
              <Button type="primary" icon="edit" onClick={() => this.handleOperate('edit')}>編輯員工</Button>
              <Button type="primary" onClick={() => this.handleOperate('detail')}>員工詳情</Button>
              <Button type="primary" icon="delete" onClick={() => this.handleOperate('delete')}>刪除員工</Button>
    </Card>
  • 關鍵:傳入不一樣的參數[type]經過判斷type的值,執行不一樣的操做ios

    //功能區操做
    handleOperate = (type) => {
            let item = this.state.selectedItem;
            if(type == 'create'){
               this.setState({
                   type,
                   isVisible: true,
                   title: '建立員工'
               })
            }else if(type == 'edit'){
               if(!item){
                   Modal.info({
                       title: '提示',
                       content: '請選擇一個用戶'
                   })
                   return;
               }
               this.setState({
                    type,
                    isVisible: true,
                    title: '編輯員工',
                    userInfo: item
               })
            }else if(type == 'detail'){
               if(!item){
                    Modal.info({
                        title: '提示',
                        content: '請選擇一個用戶'
                    })
                    return;
               } 
               this.setState({
                    type,
                    isVisible: true,
                    title: '員工詳情',
                    userInfo: item
               }) 
            }else if(type == 'delete'){
                if(!item){
                    Modal.info({
                        title: '提示',
                        content: '請選擇一個用戶'
                    })
                    return;
               }
               let _this = this;
               Modal.confirm({
                   title: '確認刪除',
                   content: `是否要刪除當前選中的員工${item.id}`,
                   onOk(){
                       axios.ajax({
                           url: '/user/delete',
                           data: {
                               params: {
                                   id: item.id
                               }
                           }
                       }).then((res) => {
                           if(res.code === 0){
                               _this.setState({
                                   isVisible: false
                               })
                               _this.requestList();
                           }
                       })
                   }
               })  
            }
    } 
  • 實例代碼:git

    import React from 'react'
    import {Card, Button, Form, Input, Select,Radio, Icon, Modal, DatePicker} from 'antd'
    import axios from './../../axios'
    import Utils from './../../utils/utils'
    import BaseForm from './../../components/BaseForm'
    import ETable from './../../components/ETable'
    import moment from 'moment'
    const FormItem = Form.Item;
    const RadioGroup = Radio.Group;
    const TextArea = Input.TextArea;
    const Option = Select.Option;
    
    export default class User extends React.Component{
    
        state = {
            list:[],
            isVisible: false
        }
    
        params = {
            page: 1
        }
        
        formList = [
            { 
                type: 'INPUT',
                label: '用戶名',
                field: 'user_name',
                placeholder: '請輸入名稱',
                width: 130
            },
            { 
                type: 'INPUT',
                label: '手機號',
                field: 'user_mobile',
                placeholder: '請輸入手機號',
                width: 130
            },
            { 
                type: 'DATE',
                label: '入職日期',
                field: 'user_date',
                placeholder: '請輸入日期'
            }
        ]
    
        componentDidMount(){
            this.requestList();
        }
    
        handleFilter = (params) => {
            this.params = params;
            this.requestList();
        }
    
        requestList = () => {
            axios.requestList(this, '/table/list1', this.params);
        }
    
        //功能區操做
        handleOperate = (type) => {
            let item = this.state.selectedItem;
            if(type == 'create'){
               this.setState({
                   type,
                   isVisible: true,
                   title: '建立員工'
               })
            }else if(type == 'edit'){
               if(!item){
                   Modal.info({
                       title: '提示',
                       content: '請選擇一個用戶'
                   })
                   return;
               }
               this.setState({
                    type,
                    isVisible: true,
                    title: '編輯員工',
                    userInfo: item
               })
            }else if(type == 'detail'){
               if(!item){
                    Modal.info({
                        title: '提示',
                        content: '請選擇一個用戶'
                    })
                    return;
               } 
               this.setState({
                    type,
                    isVisible: true,
                    title: '員工詳情',
                    userInfo: item
               }) 
            }else if(type == 'delete'){
                if(!item){
                    Modal.info({
                        title: '提示',
                        content: '請選擇一個用戶'
                    })
                    return;
               }
               let _this = this;
               Modal.confirm({
                   title: '確認刪除',
                   content: `是否要刪除當前選中的員工${item.id}`,
                   onOk(){
                       axios.ajax({
                           url: '/user/delete',
                           data: {
                               params: {
                                   id: item.id
                               }
                           }
                       }).then((res) => {
                           if(res.code === 0){
                               _this.setState({
                                   isVisible: false
                               })
                               _this.requestList();
                           }
                       })
                   }
               })  
            }
        }
    
        //建立編輯員工提交
        handleSubmit = () => {
            let type = this.state.types;
            let data = this.userForm.props.form.getFieldsValue();
            axios.ajax({
                url: type=='create'?'/user/add':'/user/edit',
                data: {
                    params: data
                }
            }).then((res) => {
                if(res.code === 0){
                   this.userForm.props.form.resetFields();
                   this.setState({
                       isVisible: false
                   })
                   this.requestList();
                }
            })
        }
    
        render(){
            const columns = [{
                title: 'id',
                dataIndex: 'id'
              }, {
                title: '用戶名',
                dataIndex: 'userName'
              }, {
                title: '性別',
                dataIndex: 'sex',
                render(sex){
                    return sex ==1 ?'男':'女'
                }
              }, {
                title: '狀態',
                dataIndex: 'state',
                render(state){
                    let config = {
                        '1':'鹹魚一條',
                        '2':'風華浪子',
                        '3':'北大才子一枚',
                        '4':'百度FE',
                        '5':'創業者'
                    }
                    return config[state];
                }
              },{
                title: '婚姻',
                dataIndex: 'isMarried',
                render(isMarried){
                    return isMarried == 1 ?'已婚':'未婚'
                }
              },{
                title: '生日',
                dataIndex: 'birthday'
              },{
                title: '聯繫地址',
                dataIndex: 'address'
              },{
                title: '早起時間',
                dataIndex: 'time'
              }
            ];
    
            let footer = {};
            if(this.state.type == 'detail'){
                footer = {
                    footer: null
                }
            }
    
            return (
                <div>
                    <Card>
                        <BaseForm formList={this.formList} filterSubmit={this.handleFilter}/>
                    </Card>
                    <Card style={{marginTop:10}} className="operate-wrap">
                        <Button type="primary" icon="plus" onClick={() => this.handleOperate('create')}>建立員工</Button>
                        <Button type="primary" icon="edit" onClick={() => this.handleOperate('edit')}>編輯員工</Button>
                        <Button type="primary" onClick={() => this.handleOperate('detail')}>員工詳情</Button>
                        <Button type="primary" icon="delete" onClick={() => this.handleOperate('delete')}>刪除員工</Button>
                    </Card>
                    <div className="content-wrap">
                        <ETable
                                columns={columns}
                                updateSelectedItem={Utils.updateSelectedItem.bind(this)}
                                selectedRowKeys={this.state.selectedRowKeys}
                                selectedItem={this.state.selectedItem}
                                dataSource={this.state.list}
                                pagination={this.state.pagination}
                        />
                    </div>
                    <Modal 
                        title={this.state.title}
                        visible={this.state.isVisible}
                        onOk={this.handleSubmit}
                        onCancel={() => {
                            this.userForm.props.form.resetFields();
                            this.setState({
                                isVisible: false
                            })
                        }}
                        width={600}
                        {...footer}
                        >
                        <UserForm type={this.state.type} userInfo={this.state.userInfo} wrappedComponentRef={(inst) => {this.userForm = inst;}}/>
                    </Modal>
                </div>
            )
        }
    }
    
    //子組件:建立員工表單
    class UserForm extends React.Component{
    
        getState = (state) => {
            let config = {
                '1':'鹹魚一條',
                '2':'風華浪子',
                '3':'北大才子一枚',
                '4':'百度FE',
                '5':'創業者'
            }
            return config[state];
        }
    
        render(){
            let type = this.props.type;
            let userInfo = this.props.userInfo || {};
            const {getFieldDecorator} = this.props.form;
            const formItemLayout= {
                labelCol:{span: 5},
                wrapperCol:{span: 19}
            }
            return (
                <Form layout="horizontal">
                      <FormItem label="用戶名" {...formItemLayout}>
                            {
                                type == 'detail' ? userInfo.userName :
                                getFieldDecorator('user_name',{
                                    initialValue: userInfo.userName
                                })(
                                    <Input type="text" placeholder="請輸入用戶名"/>
                                )
                            }
                      </FormItem>
                      <FormItem label="性別" {...formItemLayout}>
                            {
                                type == 'detail' ? userInfo.sex == 1 ? '男' : '女' :
                                getFieldDecorator('sex',{
                                    initialValue: userInfo.sex
                                })(
                                    <RadioGroup>
                                        <Radio value={1}>男</Radio>
                                        <Radio value={2}>女</Radio>
                                    </RadioGroup>
                                )
                            }
                      </FormItem>
                      <FormItem label="狀態" {...formItemLayout}>
                            {
                                type == 'detail' ? this.getState(userInfo.state) :
                                getFieldDecorator('state',{
                                    initialValue: userInfo.state
                                })(
                                    <Select>
                                        <Option value={1}>鹹魚一條</Option>
                                        <Option value={2}>風華浪子</Option>
                                        <Option value={3}>北大才子一枚</Option>
                                        <Option value={4}>百度FE</Option>
                                        <Option value={5}>創業者</Option>
                                    </Select>
                                )
                            }
                      </FormItem>
                      <FormItem label="生日" {...formItemLayout}>
                            {
                                type == 'detail' ? userInfo.birthday :
                                getFieldDecorator('birthday',{
                                    initialValue: moment(userInfo.birthday)
                                })(
                                    <DatePicker format="YYYY-MM-DD"/>
                                )
                            }
                      </FormItem>
                      <FormItem label="聯繫地址" {...formItemLayout}>
                            {
                                type == 'detail' ? userInfo.address :
                                getFieldDecorator('address',{
                                    initialValue: userInfo.address
                                })(
                                    <TextArea rows={3} placeholder="請輸入聯繫地址"/>
                                )
                            }
                      </FormItem>
                </Form>
            )
        }
    }
    UserForm = Form.create({})(UserForm);

注:項目來自慕課網github

相關文章
相關標籤/搜索