UNPKG

chowa

Version:

UI component library based on React

86 lines (85 loc) 3.43 kB
/** * @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. */ "use strict"; 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 Switch extends React.PureComponent { constructor(props) { super(props); this.state = { result: props.checked }; [ 'onChangeHandler', 'onKeyDownHandler' ].forEach((fn) => { this[fn] = this[fn].bind(this); }); } componentDidUpdate(preProps) { if (this.props.checked !== preProps.checked && this.state.result !== this.props.checked) { this.setState({ result: this.props.checked }); } } onChangeHandler(e) { const { onChange, disabled, loading } = this.props; if (onChange && !disabled && !loading) { 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(); } } render() { const { className, style, label, disabled, checkedChild, uncheckedChild, loading, tabIndex } = this.props; const { result } = this.state; const componentClass = classnames_1.default({ [utils_1.preClass('switch-wrapper')]: true, [utils_1.preClass('switch-checked')]: result, [utils_1.preClass('switch-disabled')]: disabled, [utils_1.preClass('switch-loading')]: loading, [className]: utils_1.isExist(className) }); return (React.createElement("label", { className: componentClass, style: style, tabIndex: disabled ? -1 : tabIndex, onKeyDown: disabled ? null : this.onKeyDownHandler }, React.createElement("span", { className: utils_1.preClass('switch') }, React.createElement("span", { className: utils_1.preClass('switch-circle') }), React.createElement("input", { type: 'checkbox', onChange: this.onChangeHandler, checked: result, tabIndex: -1, disabled: loading || disabled, className: utils_1.preClass('switch-input') }), checkedChild && uncheckedChild && React.createElement("span", { className: utils_1.preClass('switch-inner') }, result ? checkedChild : uncheckedChild)), utils_1.isExist(label) && React.createElement("span", { className: utils_1.preClass('switch-label') }, label))); } } Switch.propTypes = { className: PropTypes.string, style: PropTypes.object, tabIndex: PropTypes.number, label: PropTypes.string, checked: PropTypes.bool.isRequired, disabled: PropTypes.bool, loading: PropTypes.bool, onChange: PropTypes.func, checkedChild: PropTypes.node, uncheckedChild: PropTypes.node }; Switch.defaultProps = { tabIndex: 0, checked: false, loading: false, disabled: false }; exports.default = Switch;