react 使用antd的多选功能做一个单选与全选效果

一个小而简单的单选全选功能,其实官网已经给出效果了,不过是我多做了些复合用法

 

addorupdatemodal.jsx
import React from "react";
import {Modal,Table,Button,Checkbox,Card,Popconfirm } from 'antd';
import LoadingMixin from '../../../libs/loading.common.mixin';
import RequestMixin from '../../../libs/request.mixin';
import NotificationMixin from '../../../libs/notification.mixin';
import Helper from '../../../libs/helper';
import './index.css';

const { Meta } = Card;
const CheckboxGroup = Checkbox.Group;
export default React.createClass({
    mixins: [LoadingMixin, NotificationMixin, RequestMixin],
    propTypes: {
        onManualClose:React.PropTypes.func,
        onOk: React.PropTypes.func,
        onCancel: React.PropTypes.func,
        title: React.PropTypes.string,
        item: React.PropTypes.object
    },
    getInitialState() {
        return {
            item: this.props.item  && this.props.item || {},
            data: [],
            userObj: {},
            deleteList:[],
            indeterminate: false,
            checkAll: false,
            checkedList:[]
        };
    },
    componentWillMount() {
        this.fetch();
    },
    fetch() {
        // console.log("11111111111------------》",this.props.item.frameid);
        this.post({
            url: "Api/historyPush/module/frame/key/dac509bd90a82719a3569291e12c24a6f1af4bac",
            param: {
                frameid: this.props.item.frameid
                // frameid:'32frame_tj1'
            },
            noLoading: true
        }).then(result=> {
            // console.log("result-----------------",result);
            this.setState({data: result.result || []});
        });
        // this.get({
        //     url: "Api/lists/module/user/key/dac509bd90a82719a3569291e12c24a6f1af4bac",
        //     param: {
        //     },
        //     noLoading: true
        // }).then(result=> {
        //     let userObj = {};
        //     result.result && result.result.map(item => {
        //         userObj[item.id] = item.nickname;
        //     });
        //     this.setState({userObj: userObj|| {}});
        // });
    },
    hideModal() {
        this.props.onCancel && this.props.onCancel();
    },
    onChange(checkedList){
        // console.log('checked = ', checkedList);
        this.setState({
            checkedList:checkedList,
            indeterminate: !!checkedList.length && (checkedList.length < this.state.data.length),
            checkAll: checkedList.length === this.state.data.length,
        });

    },
    onCheckAllChange(e){
        // console.log("全选1",e.target.checked);
        // console.log("全选2",this.state.data);
        let dataList =[]
        for(var i=0;i<this.state.data.length;i++){
            dataList[i]=this.state.data[i].imgid
        }
        // console.log("dataList--------",dataList)
        this.setState({
            checkedList: e.target.checked ? dataList : [],
            indeterminate: false,
            checkAll: e.target.checked,
        });
    },
    handleClose(record) {
        var that = this;
        if (this.state.checkedList==null||this.state.checkedList.length==0) {
            that.error("请选择要删除的图片");
            return false;
        };
        // console.log("删除的图片",this.props.item.frameid,this.state.checkedList);
        this.post({
            url: "Api/clearCache/module/frame/key/dac509bd90a82719a3569291e12c24a6f1af4bac",
            param: {
                frameid:this.props.item.frameid,
                imglist: this.state.checkedList
            },
            noLoading: true
        }).then(result=> {
            if (result.result) {
                that.success("操作成功");
                that.fetch();
            }
        });
    },
    render() {
        let isMainObj = {
            1 : "是",
            0 : "否"
        }
        let columns = [
            { title: '用户', dataIndex: 'userid', key: 'userid', width: '20%',
                render: (text, record) => {
                    return (
                        this.state.userObj && this.state.userObj[text]
                    )
                }
            },
            { title: '主管理', dataIndex: 'is_main', key: 'is_main', width: '20%',
                render: (text, record) => {
                    return (
                        isMainObj[record['is_main']]
                    )
                }
            },
            { title: '设备备注', dataIndex: 'remark', key: 'remark', width: '30%' },
            { title: '绑定时间', dataIndex: 'create_time', key: 'create_time', width: '25%' }
        ];
        return (
            <Modal title={this.props.title && this.props.title || '新增'} visible={true}  width="700px" onCancel={this.hideModal}  maskClosable={false} footer={
                <Button key="back" type="ghost" size="large" onClick={this.hideModal}>关&nbsp;&nbsp;闭</Button>
            }>
                <div className={'boxTitle'}>
                    <Checkbox
                        indeterminate={this.state.indeterminate}
                        onChange={this.onCheckAllChange}
                        checked={this.state.checkAll}
                        // checked={this.state.checked}
                        // disabled={this.state.disabled}
                        // onChange={this.onChange} //this,record
                    >
                        {'全选'}
                    </Checkbox>
                    <Popconfirm placement="topRight" title={"您确定要删除这些数据吗?"} onConfirm={this.handleClose} okText="确定" cancelText="取消">
                        <Button type="primary">批量删除</Button>
                    </Popconfirm>
                </div>
                <div className={'cardBox'}>
                    <Checkbox.Group style={{ width: '100%' }} onChange={this.onChange}  value={this.state.checkedList}>
                    <Card title="">
                        {
                            this.state.data && this.state.data.map((item,index) => {
                                return (
                                <Card.Grid className={'gridStyle'} key={item.imgid}>
                                    <Checkbox
                                        className={'CheckboxStyle'}
                                        value={item.imgid}
                                    >
                                    </Checkbox>
                                    <img  src={item.small_url} ></img>
                                </Card.Grid>
                                )
                            })
                        }
                    </Card>
                    </Checkbox.Group>,
                </div>
            </Modal>
        )
    }
});

 

 

 

index.jsx

import React from 'react';
import { Table,Form,Input,Button,Popconfirm,Select} from 'antd';
import LoadingMixin from '../../../libs/loading.common.mixin';
import RequestMixin from '../../../libs/request.mixin';
import NotificationMixin from '../../../libs/notification.mixin';
import Helper from '../../../libs/helper';
import ModalWrapper from '../../../libs/modalwrapper';
import './index.css';
import AddOrUpdateModal from './addorupdatemodal';
import BindUserModal from './bindusermodal';

const FormItem = Form.Item;
const createForm = Form.create;
const Option = Select.Option;
let equipmentList =  React.createClass({
    mixins: [LoadingMixin,NotificationMixin,RequestMixin],
    getInitialState(){
        return {
            data: [],
            pagination: {showQuickJumper: true,showTotal: total => `共 ${total} 条`},
            loading: false,
            tableCompanyName:[],
            param:[]
        }
    },
    componentWillMount() {
        this.tableCompanyName();
    },
    tableCompanyName(){
        this.get({
            url:"Api/lists/module/company/key/dac509bd90a82719a3569291e12c24a6f1af4bac",
            param: {
            },
            noLoading: true
        }).then(result=> {
            let companyName = result.result;
            let companyMap = []
            if(companyName==null||companyName.length==0){
                companyMap =[]
            }else {
                for(var i=0;i<companyName.length;i++){
                    companyMap[companyName[i].id]=companyName[i].title;
                }
            }
            this.setState({
                tableCompanyName: companyMap,
            },this.fetch)
        });
    },
    fetch(pageNum = 1, pageSize = 10) {
        this.get({
            url: "Api/lists/module/frame/key/dac509bd90a82719a3569291e12c24a6f1af4bac",
            param: {
                companyid:this.state.param.companyid ? this.state.param.companyid :'',
                frameid:this.state.param.frameid ? this.state.param.frameid :'',
                has_kinect:this.state.param.has_kinect ? this.state.param.has_kinect :'',
                p: pageNum,
                n: pageSize
            },
            noLoading: true
        }).then(result=> {
            const pagination = this.state.pagination;
            pagination.total = Number(result.count);

            const tableList = result.result;
            const tableCompanyName = this.state.tableCompanyName;
            const companyMap = tableCompanyName;
            for (var i=0;i<tableList.length;i++){
                tableList[i].has_kinect && tableList[i].has_kinect == 0 ? tableList[i].has_kinect='普通':tableList[i].has_kinect='体感'
                if(tableList[i].companyid){
                    tableList[i].title = companyMap[tableList[i].companyid]
                }else {
                    tableList[i].title = ''
                }
            }



            this.setState({
                loading: false,
                data: tableList || [],
                pagination,
            });
        }).catch(e => {
            const pagination = this.state.pagination;
            pagination.total = 0;
            this.setState({
                loading: false,
                data: [],
                pagination,
            })
        });
    },
    handleSubmit(e) {
        var that = this;
        e && e.preventDefault();
        this.props.form.validateFieldsAndScroll((err, values) => {
            if (!err) {
                let params ={}
                params.companyid = values.companyid;
                params.frameid = values.frameid;
                params.has_kinect = values.has_kinect;
                // console.log("查询条件paramsparams",params);
                this.setState({param: params},this.tableCompanyName);
            }
        });
    },
    handleReset(e) {
        e && e.preventDefault();
        this.props.form.resetFields();
        // this.searchQuery();
    },
    handleTableChange(pagination, filters, sorter) {
        const pager = this.state.pagination;
        pager.current = pagination.current;
        this.setState({
            pagination: pager,
        });
        this.fetch(pagination.current, pagination.pageSize);
    },
    handleClose(record) {
        var that = this;
        if (!record) return;
        this.post({
            url: "Api/batchDelete/module/frame/key/dac509bd90a82719a3569291e12c24a6f1af4bac",
            param: {
                ids: record.id
            },
            noLoading: true
        }).then(result=> {
            if (result.result) {
                that.success("操作成功");
                that.fetch();
            }
        });
    },
    // addOrUpdate(modal,e) {
    //     e && e.preventDefault() ;
    //     e && e.stopPropagation();
    //     console.log("this.state.tableCompanyName----------",this.state.tableCompanyName);
    //     new ModalWrapper(AddOrUpdateModal, "addOrUpdateModal", () => {
    //         this.fetch();
    //     }, null, {
    //         shopList:this.state.shopList,
    //         title:  modal && modal.id  ? '编辑设备' : '新增设备',
    //         item: modal && modal.id ? Helper.copyObject(modal) : {},
    //         isEdit: modal && modal.id  ? true:false,
    //         tableCompanyName: modal && modal.id  ? this.state.tableCompanyName:this.state.tableCompanyName,
    //     }).show();
    // },
    handleBindCache(modal,e) {
        e && e.preventDefault() ;
        e && e.stopPropagation();
        // console.log("modal---缓存管理--",modal);
        new ModalWrapper(AddOrUpdateModal, "addOrUpdateModal", () => {
            this.fetch();
        }, null, {shopList:this.state.shopList,title:  '缓存管理',item: modal && modal.id ? Helper.copyObject(modal) : {}}).show();
    },

    handleBindUser(modal,e) {
        e && e.preventDefault() ;
        e && e.stopPropagation();
        // console.log("modal---人员管理--",modal);
        new ModalWrapper(BindUserModal, "bindUserModal", () => {
            this.fetch();
        }, null, {
            shopList:this.state.shopList,
            title:  '人员管理',
            item: modal && modal.id ? Helper.copyObject(modal) : {}
        }).show();
    },
    render() {
        const { getFieldDecorator } = this.props.form;
        let columns = [
            { title: '编号',dataIndex: 'id', key: 'id', width: '5%'},
            { title: '设备编码', dataIndex: 'frameid', key: 'frameid', width: '20%' },
            { title: '公司名称', dataIndex: 'title', key: '#2', width: '25%' },
            { title: '类型', dataIndex: 'has_kinect', key: 'has_kinect', width: '5%' },
            { title: '绑定上限', dataIndex: 'bind_limit', key: 'bind_limit', width: '5%' },
            { title: '备注', dataIndex: 'mark',key: 'mark', width: '15%'},
            { title: '操作', key: '#', width: '25%',
                render: (text, record) => {
                    return (
                        <div>
                            <Button type="primary" onClick={this.handleBindCache.bind(this,record)} style={{marginRight: "10px"}}>缓存管理</Button>
                            <Button type="primary" onClick={this.handleBindUser.bind(this,record)} style={{marginRight: "10px"}}>人员管理</Button>
                            {/*<Popconfirm placement="topRight" title={"您确定要删除该条数据吗?"} onConfirm={this.handleClose.bind(this,record)} okText="确定" cancelText="取消">*/}
                                {/*<Button type="primary" >删除</Button>*/}
                            {/*</Popconfirm>*/}
                        </div>
                    )
                }
            }
        ];
        return (
            <div className="modular-main">
                <div className="title">
                    <h2>设备管理</h2>
                </div>
                <div className="form-search">
                    <Form layout="inline" onSubmit={this.handleSubmit} autoComplete="off">
                        <FormItem>
                            {
                                getFieldDecorator('frameid')(
                                    <Input placeholder="请输入设备号"  />
                                )
                            }
                        </FormItem>
                        <FormItem>
                            {
                                getFieldDecorator('companyid',{
                                    initialValue: this.state.param && this.state.param.companyid || '',
                                })(
                                    <Select style={{ width: '120px' }}>
                                        <Option  value=""> --公司名称-- </Option>
                                        {
                                            this.state.tableCompanyName && this.state.tableCompanyName.map((item,key,index) => {
                                                // console.log("-key.toString()--------",key.toString())
                                                return (
                                                    <Option key={index} value={key.toString()}> {item}</Option>
                                                )
                                            })
                                        }
                                    </Select>
                                )
                            }
                        </FormItem>
                        <FormItem>
                            {
                                getFieldDecorator('has_kinect',{
                                    initialValue: this.state.param && this.state.param.has_kinect || '',
                                })(
                                    <Select style={{ width: '120px' }}>
                                        <Option  value=""> --请选择类型-- </Option>
                                        <Option  value="0"> 普通 </Option>
                                        <Option  value="1"> 体感 </Option>
                                    </Select>
                                )
                            }
                        </FormItem>
                        <Button type="primary" htmlType="submit">查询</Button>
                        {/*<Button type="primary" onClick={this.addOrUpdate.bind(this,'')}>添加</Button>*/}
                        {/*<Button onClick={this.handleReset}>重置</Button>*/}
                    </Form>
                </div>
                <div>
                    <Table loading={this.state.loading}
                           columns={columns}
                           dataSource={this.state.data}
                           onChange={this.handleTableChange}
                           pagination={this.state.pagination}
                           scroll={{ y: 600 }}
                           rowKey={(record) => record.id}
                    >
                    </Table>
                </div>
            </div>
        )
    }
});
equipmentList = createForm()(equipmentList);
export default equipmentList;

 

 

 

bindusermodal.jsx

import React from "react";
import {Modal,Table,Button,Popconfirm} from 'antd';
import LoadingMixin from '../../../libs/loading.common.mixin';
import RequestMixin from '../../../libs/request.mixin';
import NotificationMixin from '../../../libs/notification.mixin';
import Helper from '../../../libs/helper';

export default React.createClass({
    mixins: [LoadingMixin, NotificationMixin, RequestMixin],
    propTypes: {
        onManualClose:React.PropTypes.func,
        onOk: React.PropTypes.func,
        onCancel: React.PropTypes.func,
        title: React.PropTypes.string,
        item: React.PropTypes.object
    },
    getInitialState() {
        return {
            item: this.props.item  && this.props.item || {},
            data: [],
            userObj: {}
        };
    },
    componentWillMount() {
        this.fetch();
    },
    fetch() {
        console.log("this.props.item.frameid",this.props.item.frameid);
        this.get({
            url: "Api/getFrameUser/module/userFrame/key/dac509bd90a82719a3569291e12c24a6f1af4bac",
            param: {
                frameid: this.props.item.frameid
            },
            noLoading: true
        }).then(result=> {
            this.setState({data: result.result || []});
        });
        this.get({
            url: "Api/lists/module/user/key/dac509bd90a82719a3569291e12c24a6f1af4bac",
            param: {
            },
            noLoading: true
        }).then(result=> {
            let userObj = {};
            result.result && result.result.map(item => {
                userObj[item.id] = item.nickname;
            });
            this.setState({userObj: userObj|| {}});
        });
    },
    handleClose(record) { //解绑用户
        console.log("222222",record)
        var that = this;
        if (!record) return;
        this.post({
            url: "Api/UnbindFrame/module/userFrame/key/dac509bd90a82719a3569291e12c24a6f1af4bac",
            param: {
                userid:record.userid,
                frameid: this.props.item.frameid
            },
            noLoading: true
        }).then(result=> {
            if (result.result) {
                that.success("操作成功");
                that.fetch();
            }
        });
    },
    hideModal() {
        this.props.onCancel && this.props.onCancel();
    },
    render() {
        let isMainObj = {
            1 : "是",
            0 : "否"
        }
        let columns = [
            { title: '用户', dataIndex: 'userid', key: 'userid', width: '20%',
                render: (text, record) => {
                    return (
                        this.state.userObj && this.state.userObj[text]
                    )
                }
            },
            { title: '设备备注', dataIndex: 'remark', key: 'remark', width: '30%' },
            { title: '主管理', dataIndex: 'is_main', key: 'is_main', width: '10%',
                render: (text, record) => {
                    return (
                        isMainObj[record['is_main']]
                    )
                }
            },
            { title: '绑定时间', dataIndex: 'create_time', key: 'create_time', width: '25%' },
            { title: '操作', key: '#', width: '15%',
                render: (text, record) => {
                    return (
                        <div>
                            <Popconfirm placement="topRight" title={"您确定要解绑该条用户吗?"} onConfirm={this.handleClose.bind(this,record)} okText="确定" cancelText="取消">
                                <Button type="primary" >删除</Button>
                            </Popconfirm>
                        </div>
                    )
                }
            }
        ];
        return (
            <Modal title={this.props.title && this.props.title || '新增'} visible={true}  width="700px" onCancel={this.hideModal}  maskClosable={false} footer={
                <Button key="back" type="ghost" size="large" onClick={this.hideModal}>关&nbsp;&nbsp;闭</Button>
            }>
                <Table columns={columns}
                       dataSource={this.state.data}
                       pagination ={false}
                       scroll={{ y: 600 }}
                       rowKey={(record) => record.id}
                >
                </Table>
            </Modal>
        )
    }
});

 

 

 

 

效果图

posted @ 2019-01-03 09:49  知兮  阅读(10103)  评论(0编辑  收藏  举报