Checkbox under group also should trigger onChange

ref: #12642
This commit is contained in:
zombiej 2018-10-23 23:40:40 +08:00
parent a27c8a2740
commit 4b9027f53a
3 changed files with 22 additions and 3 deletions

View File

@ -84,7 +84,12 @@ export default class Checkbox extends React.Component<CheckboxProps, {}> {
const { checkboxGroup } = context;
let checkboxProps: CheckboxProps = { ...restProps };
if (checkboxGroup) {
checkboxProps.onChange = () => checkboxGroup.toggleOption({ label: children, value: props.value });
checkboxProps.onChange = (...args) => {
if (restProps.onChange) {
restProps.onChange(...args);
}
checkboxGroup.toggleOption({ label: children, value: props.value });
};
checkboxProps.checked = checkboxGroup.value.indexOf(props.value) !== -1;
checkboxProps.disabled = props.disabled || checkboxGroup.disabled;
}

View File

@ -4,7 +4,7 @@ import { polyfill } from 'react-lifecycles-compat';
import classNames from 'classnames';
import shallowEqual from 'shallowequal';
import omit from 'omit.js';
import Checkbox from './Checkbox';
import Checkbox, { CheckboxChangeEvent } from './Checkbox';
export type CheckboxValueType = string | number | boolean;
@ -12,6 +12,7 @@ export interface CheckboxOptionType {
label: string;
value: CheckboxValueType;
disabled?: boolean;
onChange?: (e: CheckboxChangeEvent) => void;
}
export interface AbstractCheckboxGroupProps {
@ -132,7 +133,7 @@ class CheckboxGroup extends React.Component<CheckboxGroupProps, CheckboxGroupSta
disabled={'disabled' in option ? option.disabled : props.disabled}
value={option.value}
checked={state.value.indexOf(option.value) !== -1}
onChange={() => this.toggleOption(option)}
onChange={option.onChange}
className={`${groupPrefixCls}-item`}
>
{option.label}

View File

@ -79,4 +79,17 @@ describe('CheckboxGroup', () => {
wrapper.setProps({ value: ['Apple'] });
expect(wrapper.instance().state.value).toEqual(['Apple']);
});
// https://github.com/ant-design/ant-design/issues/12642
it('should trigger onChange in sub Checkbox', () => {
const onChange = jest.fn();
const wrapper = mount(
<Checkbox.Group>
<Checkbox value="my" onChange={onChange} />
</Checkbox.Group>
);
wrapper.find('.ant-checkbox-input').at(0).simulate('change');
expect(onChange).toBeCalled();
expect(onChange.mock.calls[0][0].target.value).toEqual('my');
});
});