group.jsx 1.5 KB
Newer Older
U
ustccjw 已提交
1
import React from 'react';
A
afc163 已提交
2
import Radio from './radio';
J
jljsj 已提交
3

Y
yiminghe 已提交
4
function getCheckedValue(children) {
A
afc163 已提交
5
  let checkedValue = null;
Y
yiminghe 已提交
6
  React.Children.forEach(children, function (radio) {
Y
yiminghe 已提交
7 8 9 10 11 12 13
    if (radio.props && radio.props.checked) {
      checkedValue = radio.props.value;
    }
  });
  return checkedValue;
}

U
ustccjw 已提交
14
export default React.createClass({
J
jljsj 已提交
15 16
  getDefaultProps: function () {
    return {
Y
yiminghe 已提交
17
      prefixCls: 'ant-radio-group',
A
afc163 已提交
18
      disabled: false,
Y
yiminghe 已提交
19 20
      onChange: function () {
      }
J
jljsj 已提交
21 22 23
    };
  },
  getInitialState: function () {
A
afc163 已提交
24
    let props = this.props;
J
jljsj 已提交
25
    return {
Y
yiminghe 已提交
26
      value: props.value || props.defaultValue || getCheckedValue(props.children)
J
jljsj 已提交
27 28
    };
  },
Y
yiminghe 已提交
29 30 31 32 33 34 35
  componentWillReceiveProps(nextProps) {
    if ('value' in nextProps || getCheckedValue(nextProps.children)) {
      this.setState({
        value: nextProps.value || getCheckedValue(nextProps.children)
      });
    }
  },
J
jljsj 已提交
36
  render: function () {
A
afc163 已提交
37 38
    let props = this.props;
    let children = React.Children.map(props.children, (radio) => {
J
jljsj 已提交
39
      if (radio.props) {
40 41 42 43 44 45 46
        return (
          <Radio key={radio.props.value}
                 {...radio.props}
                 onChange={this.onRadioChange}
                 checked={this.state.value === radio.props.value}
                 disabled={radio.props.disabled || this.props.disabled}/>
        );
J
jljsj 已提交
47 48 49 50 51
      }
      return radio;
    });
    return (
      <div className={props.prefixCls}>
A
afc163 已提交
52
        {children}
J
jljsj 已提交
53 54 55 56 57
      </div>
    );
  },
  onRadioChange: function (ev) {
    this.setState({
Y
yiminghe 已提交
58
      value: ev.target.value
J
jljsj 已提交
59
    });
Y
yiminghe 已提交
60
    this.props.onChange(ev);
J
jljsj 已提交
61 62
  }
});