fix: input onSearch trigger wrongly (#34844) (#35164)

Co-authored-by: zhangqingyang@mindlinker.com <zhangqingyang@mindlinker.com>
This commit is contained in:
qyzzzz 2022-04-26 15:00:48 +08:00 committed by GitHub
parent 4a6db91365
commit 8ca52a1dda
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 43 additions and 1 deletions

View File

@ -34,11 +34,14 @@ const Search = React.forwardRef<InputRef, SearchProps>((props, ref) => {
disabled,
onSearch: customOnSearch,
onChange: customOnChange,
onCompositionStart,
onCompositionEnd,
...restProps
} = props;
const { getPrefixCls, direction } = React.useContext(ConfigContext);
const contextSize = React.useContext(SizeContext);
const composedRef = React.useRef<boolean>(false);
const size = customizeSize || contextSize;
@ -65,6 +68,13 @@ const Search = React.forwardRef<InputRef, SearchProps>((props, ref) => {
}
};
const onPressEnter = (e: React.KeyboardEvent<HTMLInputElement>) => {
if (composedRef.current) {
return;
}
onSearch(e);
};
const prefixCls = getPrefixCls('input-search', customizePrefixCls);
const inputPrefixCls = getPrefixCls('input', customizeInputPrefixCls);
@ -127,12 +137,24 @@ const Search = React.forwardRef<InputRef, SearchProps>((props, ref) => {
className,
);
const handleOnCompositionStart: React.CompositionEventHandler<HTMLInputElement> = e => {
composedRef.current = true;
onCompositionStart?.(e);
};
const handleOnCompositionEnd: React.CompositionEventHandler<HTMLInputElement> = e => {
composedRef.current = false;
onCompositionEnd?.(e);
};
return (
<Input
ref={composeRef<InputRef>(inputRef, ref)}
onPressEnter={onSearch}
onPressEnter={onPressEnter}
{...restProps}
size={size}
onCompositionStart={handleOnCompositionStart}
onCompositionEnd={handleOnCompositionEnd}
prefixCls={inputPrefixCls}
addonAfter={button}
suffix={suffix}

View File

@ -161,6 +161,26 @@ describe('Input.Search', () => {
);
});
// https://github.com/ant-design/ant-design/issues/34844
it('should not trigger onSearch when press enter using chinese inputting method', () => {
const onSearch = jest.fn();
const wrapper = mount(<Search defaultValue="search text" onSearch={onSearch} />);
wrapper.find('input').simulate('compositionStart');
wrapper.find('input').simulate('keydown', { key: 'Enter', keyCode: 13 });
expect(onSearch).not.toHaveBeenCalled();
wrapper.find('input').simulate('compositionEnd');
wrapper.find('input').simulate('keydown', { key: 'Enter', keyCode: 13 });
expect(onSearch).toHaveBeenCalledTimes(1);
expect(onSearch).toHaveBeenCalledWith(
'search text',
expect.objectContaining({
type: 'keydown',
preventDefault: expect.any(Function),
}),
);
});
// https://github.com/ant-design/ant-design/issues/14785
it('should support addonAfter', () => {
const addonAfter = <span>Addon After</span>;