chowa
Version:
UI component library based on React
85 lines (84 loc) • 3.19 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");
class Checkbox extends React.PureComponent {
constructor(props) {
super(props);
this.state = {
result: props.checked
};
[
'onChangeHandler',
'onKeyDownHandler'
].forEach((fn) => {
this[fn] = this[fn].bind(this);
});
}
onChangeHandler(e) {
const { onChange } = this.props;
if (onChange) {
onChange(e);
}
this.setState({
result: e.target.checked
});
}
onKeyDownHandler(e) {
if (e.keyCode === 13) {
const event = document.createEvent('MouseEvent');
event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
e.target.dispatchEvent(event);
e.preventDefault();
}
}
componentDidUpdate(preProps) {
if (this.props.checked !== preProps.checked && this.state.result !== this.props.checked) {
this.setState({ result: this.props.checked });
}
}
render() {
const { className, style, label, disabled, indeterminate, tabIndex } = this.props;
const { result } = this.state;
const componentClass = classnames_1.default({
[utils_1.preClass('checkbox-wrapper')]: true,
[utils_1.preClass('checkbox-checked')]: result,
[utils_1.preClass('checkbox-indeterminate')]: !result && indeterminate,
[utils_1.preClass('checkbox-disabled')]: disabled,
[className]: utils_1.isExist(className)
});
return (React.createElement("label", { className: componentClass, tabIndex: disabled ? -1 : tabIndex, onKeyDown: disabled ? null : this.onKeyDownHandler },
React.createElement("span", { style: style, className: utils_1.preClass('checkbox') },
React.createElement("input", { type: 'checkbox', onChange: this.onChangeHandler, checked: result, disabled: disabled, tabIndex: -1, className: utils_1.preClass('checkbox-input') }),
React.createElement("span", { className: utils_1.preClass('checkbox-inner') })),
utils_1.isExist(label) && React.createElement("span", { className: utils_1.preClass('checkbox-label') }, label)));
}
}
Checkbox.propTypes = {
className: PropTypes.string,
style: PropTypes.object,
tabIndex: PropTypes.number,
label: PropTypes.node,
checked: PropTypes.bool.isRequired,
disabled: PropTypes.bool,
indeterminate: PropTypes.bool,
onChange: PropTypes.func
};
Checkbox.defaultProps = {
tabIndex: 0,
checked: false,
size: 'default',
disabled: false,
indeterminate: false
};
exports.default = Checkbox;