UNPKG

chowa

Version:

UI component library based on React

83 lines (82 loc) 2.99 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"); const radio_1 = require("../radio"); class RadioGroup extends React.PureComponent { constructor(props) { super(props); this.state = { checkedValue: props.value || props.defaultValue }; } componentDidUpdate(preProps) { if (preProps.value !== this.props.value && this.state.checkedValue !== this.props.value) { this.setState({ checkedValue: this.props.value }); } } onChangeHandler(value) { this.setState({ checkedValue: value }); if (this.props.onChange) { this.props.onChange(value); } } compileOptions() { const { options, children } = this.props; const ret = [].concat(options); React.Children.forEach(children, (child) => { if (child.type === radio_1.default) { const { value, label, disabled } = child.props; ret.push({ value, label, disabled }); } }); return ret; } render() { const { className, style, mode, btn, disabled, tabIndex } = this.props; const { checkedValue } = this.state; const componentClass = classnames_1.default({ [utils_1.preClass('radio-group')]: true, [utils_1.preClass(`radio-group-${mode}`)]: true, [className]: utils_1.isExist(className) }); const options = this.compileOptions(); return (React.createElement("section", { className: componentClass, style: style }, options.map((item, key) => { return (React.createElement(radio_1.default, { key: key, btn: btn, tabIndex: tabIndex, disabled: item.disabled || disabled, checked: item.value === checkedValue, label: item.label, onChange: this.onChangeHandler.bind(this, item.value) })); }))); } } RadioGroup.propTypes = { className: PropTypes.string, style: PropTypes.object, tabIndex: PropTypes.number, options: PropTypes.array.isRequired, onChange: PropTypes.func, btn: PropTypes.bool, defaultValue: PropTypes.oneOfType([PropTypes.string, PropTypes.number, PropTypes.bool]), value: PropTypes.oneOfType([PropTypes.string, PropTypes.number, PropTypes.bool]), mode: PropTypes.oneOf(['horizontal', 'vertical']), disabled: PropTypes.bool }; RadioGroup.defaultProps = { tabIndex: 0, btn: false, options: [], mode: 'horizontal', disabled: false }; exports.default = RadioGroup;