2015-12-25 11:42:13 +08:00
|
|
|
import React from 'react';
|
|
|
|
import Checkbox from './index';
|
|
|
|
|
2016-03-28 23:21:47 +08:00
|
|
|
export default class CheckboxGroup extends React.Component {
|
|
|
|
static defaultProps = {
|
|
|
|
options: [],
|
|
|
|
defaultValue: [],
|
|
|
|
onChange() {},
|
|
|
|
}
|
|
|
|
static propTypes = {
|
2015-12-25 11:42:13 +08:00
|
|
|
defaultValue: React.PropTypes.array,
|
|
|
|
value: React.PropTypes.array,
|
|
|
|
options: React.PropTypes.array.isRequired,
|
|
|
|
onChange: React.PropTypes.func,
|
2016-03-28 23:21:47 +08:00
|
|
|
}
|
|
|
|
constructor(props) {
|
|
|
|
super(props);
|
2016-02-21 14:13:33 +08:00
|
|
|
let value;
|
|
|
|
if ('value' in props) {
|
|
|
|
value = props.value;
|
|
|
|
} else if ('defaultValue' in props) {
|
|
|
|
value = props.defaultValue;
|
|
|
|
}
|
2016-03-28 23:21:47 +08:00
|
|
|
this.state = { value };
|
|
|
|
}
|
2015-12-25 11:42:13 +08:00
|
|
|
componentWillReceiveProps(nextProps) {
|
|
|
|
if ('value' in nextProps) {
|
|
|
|
this.setState({
|
2016-01-14 19:15:21 +08:00
|
|
|
value: nextProps.value || [],
|
2015-12-25 11:42:13 +08:00
|
|
|
});
|
|
|
|
}
|
2016-03-28 23:21:47 +08:00
|
|
|
}
|
2016-03-09 21:08:08 +08:00
|
|
|
getOptions() {
|
|
|
|
const { options } = this.props;
|
|
|
|
return options.map(option => {
|
|
|
|
if (typeof option === 'string') {
|
|
|
|
return {
|
|
|
|
label: option,
|
|
|
|
value: option,
|
|
|
|
};
|
|
|
|
}
|
|
|
|
return option;
|
|
|
|
});
|
2016-03-28 23:21:47 +08:00
|
|
|
}
|
|
|
|
toggleOption = (option) => {
|
2016-03-09 21:08:08 +08:00
|
|
|
const optionIndex = this.state.value.indexOf(option.value);
|
2016-03-01 17:01:03 +08:00
|
|
|
const value = [...this.state.value];
|
2015-12-25 11:42:13 +08:00
|
|
|
if (optionIndex === - 1) {
|
2016-03-09 21:08:08 +08:00
|
|
|
value.push(option.value);
|
2015-12-25 11:42:13 +08:00
|
|
|
} else {
|
|
|
|
value.splice(optionIndex, 1);
|
|
|
|
}
|
|
|
|
if (!('value' in this.props)) {
|
|
|
|
this.setState({ value });
|
|
|
|
}
|
|
|
|
this.props.onChange(value);
|
2016-03-28 23:21:47 +08:00
|
|
|
}
|
2015-12-25 11:42:13 +08:00
|
|
|
render() {
|
2016-03-09 21:08:08 +08:00
|
|
|
const options = this.getOptions();
|
2016-01-07 14:21:29 +08:00
|
|
|
return (
|
|
|
|
<div className="ant-checkbox-group">
|
|
|
|
{
|
|
|
|
options.map(option =>
|
2016-03-17 11:10:58 +08:00
|
|
|
<Checkbox disabled={'disabled' in option ? option.disabled : this.props.disabled}
|
2016-03-09 21:08:08 +08:00
|
|
|
checked={this.state.value.indexOf(option.value) !== -1}
|
2016-03-30 17:06:19 +08:00
|
|
|
onChange={() => this.toggleOption(option)}
|
2016-03-09 21:08:08 +08:00
|
|
|
className="ant-checkbox-group-item" key={option.value}>
|
|
|
|
{option.label}
|
2016-02-17 18:02:33 +08:00
|
|
|
</Checkbox>
|
2016-01-07 14:21:29 +08:00
|
|
|
)
|
|
|
|
}
|
|
|
|
</div>
|
|
|
|
);
|
2016-03-28 23:21:47 +08:00
|
|
|
}
|
|
|
|
}
|