UNPKG

chowa

Version:

UI component library based on React

82 lines (81 loc) 3.06 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 Radio 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.props.checked !== this.state.result) { this.setState({ result: this.props.checked }); } } render() { const { className, style, label, disabled, btn, tabIndex } = this.props; const { result } = this.state; const componentClass = classnames_1.default({ [utils_1.preClass('radio-wrapper')]: !btn, [utils_1.preClass('radio-btn')]: btn, [utils_1.preClass('radio-checked')]: result, [utils_1.preClass('radio-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", { className: utils_1.preClass('radio'), style: style }, React.createElement("input", { type: 'radio', tabIndex: -1, onChange: this.onChangeHandler, checked: result, disabled: disabled, className: utils_1.preClass('radio-input') }), !btn && React.createElement("span", { className: utils_1.preClass('radio-inner') })), utils_1.isExist(label) && React.createElement("span", { className: utils_1.preClass('radio-label') }, label))); } } Radio.propTypes = { className: PropTypes.string, style: PropTypes.object, tabIndex: PropTypes.number, label: PropTypes.node, checked: PropTypes.bool.isRequired, disabled: PropTypes.bool, btn: PropTypes.bool, onChange: PropTypes.func }; Radio.defaultProps = { tabIndex: 0, checked: false, btn: false, disabled: false }; exports.default = Radio;