Skip to content

Commit

Permalink
fix: Search crash in AutoComplete (ant-design#25049)
Browse files Browse the repository at this point in the history
  • Loading branch information
zombieJ authored Jun 17, 2020
1 parent 395c0c8 commit dc4b420
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 5 deletions.
11 changes: 6 additions & 5 deletions components/input/Search.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import * as React from 'react';
import classNames from 'classnames';
import { composeRef } from 'rc-util/lib/ref';
import SearchOutlined from '@ant-design/icons/SearchOutlined';
import LoadingOutlined from '@ant-design/icons/LoadingOutlined';
import Input, { InputProps } from './Input';
Expand All @@ -21,8 +22,8 @@ export interface SearchProps extends InputProps {
loading?: boolean;
}

const Search = React.forwardRef<unknown, SearchProps>((props, ref) => {
const inputRef = (ref as any) || React.createRef<Input>();
const Search = React.forwardRef<Input, SearchProps>((props, ref) => {
const inputRef = React.useRef<Input>(null);

const onChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const { onChange: customOnChange, onSearch: customOnSearch } = props;
Expand All @@ -35,7 +36,7 @@ const Search = React.forwardRef<unknown, SearchProps>((props, ref) => {
};

const onMouseDown: React.MouseEventHandler<HTMLElement> = e => {
if (document.activeElement === inputRef.current.input) {
if (document.activeElement === inputRef.current?.input) {
e.preventDefault();
}
};
Expand All @@ -46,7 +47,7 @@ const Search = React.forwardRef<unknown, SearchProps>((props, ref) => {
return;
}
if (customOnSearch) {
customOnSearch(inputRef.current.input.value, e);
customOnSearch(inputRef.current?.input.value!, e);
}
};

Expand Down Expand Up @@ -183,7 +184,7 @@ const Search = React.forwardRef<unknown, SearchProps>((props, ref) => {
<SizeContext.Consumer>
{size => (
<Input
ref={inputRef}
ref={composeRef<Input>(inputRef, ref)}
onPressEnter={onSearch}
{...restProps}
size={customizeSize || size}
Expand Down
8 changes: 8 additions & 0 deletions components/input/__tests__/Search.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -201,4 +201,12 @@ describe('Input.Search', () => {
expect(prevented).toBeTruthy();
expect(document.activeElement).toBe(wrapper.find('input').at(0).getDOMNode());
});

it('not crash when use function ref', () => {
const ref = jest.fn();
const wrapper = mount(<Search ref={ref} enterButton />);
expect(() => {
wrapper.find('button').simulate('mousedown');
}).not.toThrow();
});
});

0 comments on commit dc4b420

Please sign in to comment.