CheckBox.jsx 2.5 KB
Newer Older
徐立's avatar
徐立 committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
/**
 * 移动端复选框封装
 */
import React, { Component } from 'react'
import { Checkbox, Flex } from 'antd-mobile';
const AgreeItem = Checkbox.AgreeItem;
export default class CheckBox extends Component {
    constructor(props){
        super(props)
        const value = props.value || {};
        this.state = {
            list:!!value.list?value.list:[]
        }
    }
    triggerChange = (changedValue) => {
        // Should provide an event to pass value to Form.
        const onChange = this.props.onChange;
            if (onChange) {
                this.setState({
                    list:changedValue.list
                })
                // 传入数据源错误导致web端和移动端冲突修改为以下传入
                onChange(changedValue.list);
        }
    }
    componentWillReceiveProps(nextProps) {
        // Should be a controlled component.
        if ('value' in nextProps) {
            const value = nextProps.value;
            this.setState(value);
        }
    }
    handelChange = (value) => {
        let { list } = this.state
        if(list.includes(value)){
            // if (!('value' in this.props)) {
                this.triggerChange({list:this.state.list.filter(item=>item!==value)});
            // }
        }else {
            // if (!('value' in this.props)) {
                this.triggerChange({list:[...list,value]});
            // }
        }
    }
    /**
     * 是否默认选中
     */
    getChecked = (value) => {
        let isArray = Array.isArray
        if(this.props.value){
                if(isArray( this.props.value )){
                    let list = this.props.value
                    return !!list?list.includes(value):false
                } else {
                    let { list } = this.props.value
                    return !!list?list.includes(value):false
                }
        }
    }
    render() {
        let { options,initValue } = this.props
        return (
            <div>
                {
                    options.map((item,index) => {
                        return (
                            <Flex.Item>
                                <AgreeItem key={index} defaultChecked={this.getChecked(item.value)}  onChange={()=>{this.handelChange(item.value)}}>
                                    {item.label}
                                </AgreeItem>
                            </Flex.Item>
                        )
                    })
                }
            </div>
        )
    }
}