Merge pull request #17342 from yoyo837/checkbox-onchange-sort

fix: CheckboxGroup onChange 值保持选项的顺序
This commit is contained in:
偏右 2019-06-28 13:44:49 +08:00 committed by GitHub
commit b5d16a6bd1
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 44 additions and 1 deletions

View File

@ -136,7 +136,16 @@ class CheckboxGroup extends React.Component<CheckboxGroupProps, CheckboxGroupSta
}
const onChange = this.props.onChange;
if (onChange) {
onChange(value.filter(val => registeredValues.indexOf(val) !== -1));
const options = this.getOptions();
onChange(
value
.filter(val => registeredValues.indexOf(val) !== -1)
.sort((a, b) => {
const indexA = options.findIndex(opt => opt.value === a);
const indexB = options.findIndex(opt => opt.value === b);
return indexA - indexB;
}),
);
}
};

View File

@ -133,4 +133,38 @@ describe('CheckboxGroup', () => {
expect(onChange).toHaveBeenCalledWith([2]);
});
// https://github.com/ant-design/ant-design/issues/17297
it('onChange should keep the order of the original values', () => {
const onChange = jest.fn();
const wrapper = mount(
<Checkbox.Group onChange={onChange}>
<Checkbox key={1} value={1} />
<Checkbox key={2} value={2} />
<Checkbox key={3} value={3} />
<Checkbox key={4} value={4} />
</Checkbox.Group>,
);
wrapper
.find('.ant-checkbox-input')
.at(0)
.simulate('change');
expect(onChange).toHaveBeenCalledWith([1]);
wrapper
.find('.ant-checkbox-input')
.at(1)
.simulate('change');
expect(onChange).toHaveBeenCalledWith([1, 2]);
wrapper
.find('.ant-checkbox-input')
.at(0)
.simulate('change');
expect(onChange).toHaveBeenCalledWith([2]);
wrapper
.find('.ant-checkbox-input')
.at(0)
.simulate('change');
expect(onChange).toHaveBeenCalledWith([1, 2]);
});
});