chowa
Version:
UI component library based on React
93 lines (92 loc) • 3.3 kB
JavaScript
/**
* @license chowa v1.1.3
*
* Copyright (c) Chowa Techonlogies Co.,Ltd.(http://www.chowa.cn).
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
;
Object.defineProperty(exports, "__esModule", { value: true });
const React = require("react");
const PropTypes = require("prop-types");
const classnames_1 = require("classnames");
const utils_1 = require("../utils");
const checkbox_1 = require("../checkbox");
class CheckboxGroup extends React.PureComponent {
constructor(props) {
super(props);
this.state = {
checkedValues: props.value || props.defaultValue || []
};
}
componentDidUpdate(preProps) {
if (!utils_1.isEqual(preProps.value, this.props.value) && !utils_1.isEqual(this.props.value, this.state.checkedValues)) {
this.setState({ checkedValues: this.props.value || [] });
}
}
onChangeHandler(value, e) {
const { checkedValues } = this.state;
const { onChange } = this.props;
const newcheckedValues = [].concat(checkedValues);
if (e.target.checked) {
newcheckedValues.push(value);
}
else {
newcheckedValues.splice(newcheckedValues.indexOf(value), 1);
}
this.setState({
checkedValues: newcheckedValues
}, () => {
if (onChange) {
onChange(newcheckedValues);
}
});
}
compileOptions() {
const { options, children } = this.props;
const ret = [].concat(options);
React.Children.forEach(children, (child) => {
if (utils_1.isReactElement(child) && child.type === checkbox_1.default) {
const { value, label, disabled } = child.props;
ret.push({
value,
label,
disabled
});
}
});
return ret;
}
render() {
const { checkedValues } = this.state;
const { className, style, disabled, mode, tabIndex } = this.props;
const componentClass = classnames_1.default({
[utils_1.preClass('checkbox-group')]: true,
[utils_1.preClass(`checkbox-group-${mode}`)]: true,
[className]: utils_1.isExist(className)
});
const options = this.compileOptions();
return (React.createElement("section", { style: style, className: componentClass }, options.map((item, key) => {
return (React.createElement(checkbox_1.default, { key: key, tabIndex: tabIndex, checked: checkedValues.includes(item.value), label: item.label, disabled: item.disabled || disabled, onChange: this.onChangeHandler.bind(this, item.value) }));
})));
}
}
CheckboxGroup.propTypes = {
className: PropTypes.string,
style: PropTypes.object,
tabIndex: PropTypes.number,
options: PropTypes.array,
onChange: PropTypes.func,
defaultValue: PropTypes.array,
value: PropTypes.array,
mode: PropTypes.oneOf(['horizontal', 'vertical']),
disabled: PropTypes.bool
};
CheckboxGroup.defaultProps = {
tabIndex: 0,
options: [],
mode: 'horizontal',
disabled: false
};
exports.default = CheckboxGroup;