diff --git a/components/input/Search.tsx b/components/input/Search.tsx index 7f916e829f34..3d567769ea96 100644 --- a/components/input/Search.tsx +++ b/components/input/Search.tsx @@ -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'; @@ -21,8 +22,8 @@ export interface SearchProps extends InputProps { loading?: boolean; } -const Search = React.forwardRef((props, ref) => { - const inputRef = (ref as any) || React.createRef(); +const Search = React.forwardRef((props, ref) => { + const inputRef = React.useRef(null); const onChange = (e: React.ChangeEvent) => { const { onChange: customOnChange, onSearch: customOnSearch } = props; @@ -35,7 +36,7 @@ const Search = React.forwardRef((props, ref) => { }; const onMouseDown: React.MouseEventHandler = e => { - if (document.activeElement === inputRef.current.input) { + if (document.activeElement === inputRef.current?.input) { e.preventDefault(); } }; @@ -46,7 +47,7 @@ const Search = React.forwardRef((props, ref) => { return; } if (customOnSearch) { - customOnSearch(inputRef.current.input.value, e); + customOnSearch(inputRef.current?.input.value!, e); } }; @@ -183,7 +184,7 @@ const Search = React.forwardRef((props, ref) => { {size => ( (inputRef, ref)} onPressEnter={onSearch} {...restProps} size={customizeSize || size} diff --git a/components/input/__tests__/Search.test.js b/components/input/__tests__/Search.test.js index 3ebf2bfffd97..3ff37720e61d 100644 --- a/components/input/__tests__/Search.test.js +++ b/components/input/__tests__/Search.test.js @@ -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(); + expect(() => { + wrapper.find('button').simulate('mousedown'); + }).not.toThrow(); + }); });