UNPKG

3.38 kBJavaScriptView Raw
1import React from 'react';
2import PropTypes from 'prop-types';
3import Checkbox from './Checkbox';
4import isEqual from 'lodash.isequal'
5
6
7const propTypes = {
8 clsPrefix:PropTypes.string,
9 value:PropTypes.array,
10 onChange:PropTypes.func,
11 disabled: PropTypes.bool,
12 options: PropTypes.array,
13 defaultValue: PropTypes.array
14};
15
16const defaultProps = {
17 clsPrefix:'u-checkbox-group',
18 onChange:()=>{},
19 disabled: false,
20 options: []
21};
22class CheckboxGroup extends React.Component {
23 constructor(props) {
24 super(props);
25 this.state = {
26 values: props.value || props.defaultValue || [],
27 }
28 }
29 componentWillReceiveProps(nextProps){
30 if(!isEqual(nextProps.value,this.state.values)){
31 this.setState({
32 values:nextProps.value
33 })
34 }
35 }
36 changeHandle=(v)=>{
37 let values = this.state.values;
38 if(values.indexOf(v)!=-1){
39 values.splice(values.indexOf(v),1)
40 }else{
41 values.push(v)
42 }
43 this.setState({
44 values
45 })
46 const { onChange } = this.props;
47 if (onChange) {
48 const options = this.getOptions();
49 onChange(
50 values
51 .filter(val => values.indexOf(val) !== -1)
52 .sort((a, b) => {
53 const indexA = options.findIndex(opt => opt.value === a);
54 const indexB = options.findIndex(opt => opt.value === b);
55 return indexA - indexB;
56 }),
57 );
58 }
59 }
60
61 getOptions() {
62 const { options } = this.props;
63 return (options).map(option => {
64 if (typeof option === 'string') {
65 return {
66 label: option,
67 value: option,
68 }
69 }
70 return option;
71 });
72 }
73
74 render() {
75 let state = this.state;
76 let props = this.props;
77 let { clsPrefix, className, disabled, children, options } = props;
78 let classes = clsPrefix;
79 if(className)classes += ' '+className;
80 if (options && options.length > 0) {
81 children = this.getOptions().map(option => (
82 <Checkbox
83 key={option.value.toString()}
84 disabled={'disabled' in option ? option.disabled : props.disabled}
85 value={option.value}
86 checked={state.values.indexOf(option.value) !== -1}
87 onChange={option.onChange}
88 >
89 {option.label}
90 </Checkbox>
91 ));
92 }
93 return (
94 <div className={classes} >
95 {
96 React.Children.map(children,child=>React.cloneElement(child,
97 {
98 onChange:()=>{this.changeHandle(child.props.value)},
99 checked:state.values.indexOf(child.props.value)!=-1,
100 disabled: child.props.disabled || disabled
101 }
102 ))
103 }
104 </div>
105 );
106 }
107}
108
109CheckboxGroup.propTypes = propTypes;
110CheckboxGroup.defaultProps = defaultProps;
111
112export default CheckboxGroup;