fix onChange e.target.value when clear

This commit is contained in:
afc163 2018-12-28 15:48:05 +08:00 committed by 偏右
parent cb57ff103b
commit d19f406f86
2 changed files with 50 additions and 5 deletions

View File

@ -128,12 +128,23 @@ class Input extends React.Component<InputProps, any> {
if (!('value' in this.props)) {
this.setState({ value });
}
const newEvent = Object.create(e);
const eventTarget = this.input;
newEvent.target = eventTarget;
newEvent.currentTarget = eventTarget;
let event = e;
if (e.type === 'click') { // click clear icon
event = Object.create(e);
event.target = this.input;
event.currentTarget = this.input;
const originalInputValue = this.input.value;
// change input value cause e.target.value should be '' when clear input
this.input.value = '';
if (onChange) {
onChange(event as React.ChangeEvent<HTMLInputElement>);
}
// reset input value
this.input.value = originalInputValue;
return;
}
if (onChange) {
onChange(newEvent);
onChange(event as React.ChangeEvent<HTMLInputElement>);
}
}

View File

@ -133,4 +133,38 @@ describe('Input allowClear', () => {
expect(wrapper).toMatchSnapshot();
expect(wrapper.find('input').getDOMNode().value).toEqual('');
});
it('should trigger event correctly', () => {
let argumentEventObject;
let argumentEventObjectValue;
const onChange = e => {
argumentEventObject = e;
argumentEventObjectValue = e.target.value;
};
const wrapper = mount(<Input allowClear defaultValue="111" onChange={onChange} />);
wrapper
.find('.ant-input-clear-icon')
.at(0)
.simulate('click');
expect(argumentEventObject.type).toBe('click');
expect(argumentEventObjectValue).toBe('');
expect(wrapper.find('input').at(0).getDOMNode().value).toBe('');
});
it('should trigger event correctly on controlled mode', () => {
let argumentEventObject;
let argumentEventObjectValue;
const onChange = e => {
argumentEventObject = e;
argumentEventObjectValue = e.target.value;
};
const wrapper = mount(<Input allowClear value="111" onChange={onChange} />);
wrapper
.find('.ant-input-clear-icon')
.at(0)
.simulate('click');
expect(argumentEventObject.type).toBe('click');
expect(argumentEventObjectValue).toBe('');
expect(wrapper.find('input').at(0).getDOMNode().value).toBe('111');
});
});