Skip to content

Commit

Permalink
fix: update prevValue of checkbox if value changed (ant-design#33753)
Browse files Browse the repository at this point in the history
  • Loading branch information
MadCcc authored and Amour1688 committed Jan 30, 2022
1 parent fcb8ab0 commit d64713f
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 1 deletion.
1 change: 1 addition & 0 deletions components/checkbox/Checkbox.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ const InternalCheckbox: React.ForwardRefRenderFunction<HTMLInputElement, Checkbo
if (restProps.value !== prevValue.current) {
checkboxGroup?.cancelValue(prevValue.current);
checkboxGroup?.registerValue(restProps.value);
prevValue.current = restProps.value;
}
return () => checkboxGroup?.cancelValue(restProps.value);
}, [restProps.value]);
Expand Down
39 changes: 38 additions & 1 deletion components/checkbox/__tests__/group.test.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import React from 'react';
import React, { useState } from 'react';
import { mount, render } from 'enzyme';
import Collapse from '../../collapse';
import Table from '../../table';
import Checkbox from '../index';
import mountTest from '../../../tests/shared/mountTest';
import rtlTest from '../../../tests/shared/rtlTest';
import Input from '../../input';

describe('CheckboxGroup', () => {
mountTest(Checkbox.Group);
Expand Down Expand Up @@ -222,4 +223,40 @@ describe('CheckboxGroup', () => {
wrapper.find('.ant-checkbox-input').at(0).simulate('change');
expect(onChange).toHaveBeenCalledWith([1]);
});

it('should store latest checkbox value if changed', () => {
const onChange = jest.fn();

const Demo = () => {
const [v, setV] = useState('');

React.useEffect(() => {
setTimeout(setV('1'), 1000);
}, []);

return (
<div>
<Input className="my-input" value={v} onChange={e => setV(e.target.value)} />
<Checkbox.Group defaultValue={['length1']} style={{ width: '100%' }} onChange={onChange}>
<Checkbox className="target-checkbox" value={v ? `length${v}` : 'A'}>
A
</Checkbox>
</Checkbox.Group>
</div>
);
};

const wrapper = mount(<Demo />);

wrapper.find('.ant-checkbox-input').first().simulate('change');
expect(onChange).toHaveBeenCalledWith([]);
wrapper.find('.ant-checkbox-input').first().simulate('change');
expect(onChange).toHaveBeenCalledWith(['length1']);
wrapper
.find('.ant-input')
.first()
.simulate('change', { target: { value: '' } });
wrapper.find('.ant-checkbox-input').first().simulate('change');
expect(onChange).toHaveBeenCalledWith(['A']);
});
});

0 comments on commit d64713f

Please sign in to comment.