-
Notifications
You must be signed in to change notification settings - Fork 439
Expand file tree
/
Copy pathCheckBoxGroup.jsx
More file actions
97 lines (79 loc) · 2.21 KB
/
CheckBoxGroup.jsx
File metadata and controls
97 lines (79 loc) · 2.21 KB
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
/* @flow */
import * as React from 'react';
import { Component, PropTypes } from '../../libs'
type State = {
options: Array<string>,
}
export default class CheckboxGroup extends Component {
state: State;
constructor(props: Object) {
super(props);
this.state = {
options: this.props.value || []
};
}
componentWillReceiveProps(nextProps: Object): void {
if (nextProps.value !== this.props.value) {
this.setState({
options: nextProps.value
});
}
}
getChildContext(): { ElCheckboxGroup: CheckboxGroup } {
return {
ElCheckboxGroup: this
};
}
onChange(value: string, checked: boolean): void {
const index = this.state.options.indexOf(value);
if (checked) {
if (index === -1) {
this.state.options.push(value);
}
} else {
this.state.options.splice(index, 1);
}
this.forceUpdate();
if (this.props.onChange) {
this.props.onChange(this.state.options);
}
}
render(): React.Element<any> {
const { options } = this.state;
const children = React.Children.map(this.props.children, (child, index) => {
if (!child) {
return null;
}
const { elementType } = child.type;
// 过滤非Checkbox和CheckboxButton的子组件
if (elementType !== 'Checkbox' && elementType !== 'CheckboxButton') {
return null;
}
return React.cloneElement(
child,
Object.assign({}, child.props, {
key: index,
checked: child.props.checked || options.indexOf(child.props.value) >= 0 || options.indexOf(child.props.label) >= 0 ,
onChange: this.onChange.bind(this, child.props.value || child.props.label),
}),
);
});
return (
<div style={this.style()} className={this.className('el-checkbox-group')}>
{children}
</div>
)
}
}
CheckboxGroup.childContextTypes = {
ElCheckboxGroup: PropTypes.any
};
CheckboxGroup.propTypes = {
min: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
max: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
size: PropTypes.string,
fill: PropTypes.string,
textColor: PropTypes.string,
value: PropTypes.any,
onChange: PropTypes.func,
};