ant-design/components/radio/group.jsx

63 lines
1.5 KiB
React
Raw Normal View History

import React from 'react';
2015-07-17 16:06:46 +08:00
2015-07-20 22:36:49 +08:00
function getCheckedValue(children) {
2015-09-01 16:18:46 +08:00
let checkedValue = null;
2015-08-27 13:34:38 +08:00
React.Children.forEach(children, function (radio) {
2015-07-20 22:36:49 +08:00
if (radio.props && radio.props.checked) {
checkedValue = radio.props.value;
}
});
return checkedValue;
}
export default React.createClass({
getDefaultProps() {
2015-07-17 16:06:46 +08:00
return {
2015-07-20 22:36:49 +08:00
prefixCls: 'ant-radio-group',
disabled: false,
2016-01-21 22:45:21 +08:00
size: 'default',
onChange() {
2015-07-20 22:36:49 +08:00
}
2015-07-17 16:06:46 +08:00
};
},
getInitialState() {
2015-09-01 16:18:46 +08:00
let props = this.props;
2015-07-17 16:06:46 +08:00
return {
2015-07-20 22:36:49 +08:00
value: props.value || props.defaultValue || getCheckedValue(props.children)
2015-07-17 16:06:46 +08:00
};
},
2015-07-20 22:36:49 +08:00
componentWillReceiveProps(nextProps) {
if ('value' in nextProps || getCheckedValue(nextProps.children)) {
this.setState({
value: nextProps.value || getCheckedValue(nextProps.children)
});
}
},
2016-01-21 22:45:21 +08:00
onRadioChange(ev) {
this.setState({
value: ev.target.value
});
this.props.onChange(ev);
},
render() {
2016-01-21 22:45:21 +08:00
const props = this.props;
const children = React.Children.map(props.children, (radio) => {
2015-07-17 16:06:46 +08:00
if (radio.props) {
2016-01-21 22:45:21 +08:00
return React.cloneElement(radio, {
key: radio.props.value,
...radio.props,
onChange: this.onRadioChange,
checked: this.state.value === radio.props.value,
disabled: radio.props.disabled || this.props.disabled,
});
2015-07-17 16:06:46 +08:00
}
return radio;
});
return (
2016-01-21 22:45:21 +08:00
<div className={`${props.prefixCls} ${props.prefixCls}-${props.size}`}>
2015-07-17 16:43:20 +08:00
{children}
2015-07-17 16:06:46 +08:00
</div>
);
},
});