-
-
Notifications
You must be signed in to change notification settings - Fork 227
/
CheckboxGroup.jsx
107 lines (94 loc) · 2.71 KB
/
CheckboxGroup.jsx
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
import React, { PureComponent, cloneElement } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
function getCheckedValue(children) {
const checkedValue = [];
React.Children.forEach(children, (checkbox) => {
if (checkbox.props && checkbox.props.checked) {
checkedValue.push(checkbox.props.value);
}
});
return checkedValue;
}
class CheckboxGroup extends PureComponent {
constructor(props) {
super(props);
this.state = {
value: props.value || props.defaultValue || getCheckedValue(props.children),
};
}
componentWillReceiveProps(nextProps) {
if ('value' in nextProps || getCheckedValue(nextProps.children)) {
this.setState({
value: nextProps.value || nextProps.defaultValue || getCheckedValue(nextProps.children),
});
}
}
onCheckboxChange(value) {
const values = this.state.value;
const index = values.indexOf(value);
if (index < 0) {
values.push(value);
} else {
values.splice(index, 1);
}
this.setState({
value: values,
});
this.props.onChange(values);
}
render() {
const { prefixCls, className, theme, shape, type, block, disabled, compact, children } = this.props;
const items = React.Children.map(children, (element, index) => {
return cloneElement(element, {
key: index,
type,
theme,
block: block || element.props.block,
disabled: disabled || element.props.disabled,
onChange: () => this.onCheckboxChange(element.props.value),
checked: (this.state.value.indexOf(element.props.value) > -1),
});
});
const cls = classnames({
[`${prefixCls}`]: true,
[className]: !!className,
[`shape-${shape}`]: !!shape,
'is-compact': compact,
block,
disabled,
});
return (
<div className={cls}>
{items}
</div>
);
}
}
CheckboxGroup.propTypes = {
prefixCls: PropTypes.string,
className: PropTypes.string,
theme: PropTypes.oneOf(['default', 'primary', 'info', 'success', 'warning', 'error']),
shape: PropTypes.oneOf(['radius', 'round']),
type: PropTypes.oneOf(['button', 'cell']),
value: PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.string, PropTypes.number])),
defaultValue: PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.string, PropTypes.number])),
block: PropTypes.bool,
disabled: PropTypes.bool,
compact: PropTypes.bool,
onChange: PropTypes.func,
};
CheckboxGroup.defaultProps = {
prefixCls: 'za-checkbox-group',
className: null,
theme: 'primary',
shape: null,
type: null,
value: null,
defaultValue: null,
block: false,
disabled: false,
compact: false,
onChange() {},
};
export default CheckboxGroup;