diff --git a/components/radio/__tests__/group.test.js b/components/radio/__tests__/group.test.js index ecbd14350f..8328285aff 100644 --- a/components/radio/__tests__/group.test.js +++ b/components/radio/__tests__/group.test.js @@ -68,6 +68,37 @@ describe('Radio', () => { expect(onChange.mock.calls.length).toBe(2); }); + it('both of radio and radioGroup will trigger onchange event when they exists', () => { + const onChange = jest.fn(); + const onChangeRadioGroup = jest.fn(); + + const wrapper = mount( + + + A + + + B + + + C + + , + ); + const radios = wrapper.find('input'); + + // uncontrolled component + wrapper.setState({ value: 'B' }); + radios.at(0).simulate('change'); + expect(onChange.mock.calls.length).toBe(1); + expect(onChangeRadioGroup.mock.calls.length).toBe(1); + + // controlled component + wrapper.setProps({ value: 'A' }); + radios.at(1).simulate('change'); + expect(onChange.mock.calls.length).toBe(2); + }); + it("won't fire change events when value not changes", () => { const onChange = jest.fn(); diff --git a/components/radio/radio.tsx b/components/radio/radio.tsx index 43d87bcbaa..ffb0b81584 100644 --- a/components/radio/radio.tsx +++ b/components/radio/radio.tsx @@ -5,7 +5,7 @@ import classNames from 'classnames'; import shallowEqual from 'shallowequal'; import RadioGroup from './group'; import RadioButton from './radioButton'; -import { RadioProps, RadioGroupContext } from './interface'; +import { RadioProps, RadioChangeEvent, RadioGroupContext } from './interface'; import { ConfigConsumer, ConfigConsumerProps } from '../config-provider'; export default class Radio extends React.Component { @@ -44,6 +44,16 @@ export default class Radio extends React.Component { this.rcCheckbox = node; }; + onChange = (e: RadioChangeEvent) => { + if (this.props.onChange) { + this.props.onChange(e); + } + + if (this.context.radioGroup && this.context.radioGroup.onChange) { + this.context.radioGroup.onChange(e); + } + }; + renderRadio = ({ getPrefixCls }: ConfigConsumerProps) => { const { props, context } = this; const { prefixCls: customizePrefixCls, className, children, style, ...restProps } = props; @@ -52,7 +62,7 @@ export default class Radio extends React.Component { const radioProps: RadioProps = { ...restProps }; if (radioGroup) { radioProps.name = radioGroup.name; - radioProps.onChange = radioGroup.onChange; + radioProps.onChange = this.onChange; radioProps.checked = props.value === radioGroup.value; radioProps.disabled = props.disabled || radioGroup.disabled; }