diff --git a/src/Input.tsx b/src/Input.tsx index 261f14d..7ab86fb 100644 --- a/src/Input.tsx +++ b/src/Input.tsx @@ -23,6 +23,7 @@ const Input = forwardRef((props, ref) => { onBlur, onPressEnter, onKeyDown, + onKeyUp, prefixCls = 'rc-input', disabled, htmlSize, @@ -42,6 +43,7 @@ const Input = forwardRef((props, ref) => { const [focused, setFocused] = useState(false); const compositionRef = useRef(false); + const keyLockRef = useRef(false); const inputRef = useRef(null); const holderRef = useRef(null); @@ -155,10 +157,17 @@ const Input = forwardRef((props, ref) => { }; const handleKeyDown = (e: React.KeyboardEvent) => { - if (onPressEnter && e.key === 'Enter') { + onKeyDown?.(e); + if (onPressEnter && e.key === 'Enter' && !keyLockRef.current) { + keyLockRef.current = true; onPressEnter(e); } - onKeyDown?.(e); + }; + const handleKeyUp = (e: React.KeyboardEvent) => { + onKeyUp?.(e); + if (e.key === 'Enter') { + keyLockRef.current = false; + } }; const handleFocus: React.FocusEventHandler = (e) => { @@ -215,6 +224,7 @@ const Input = forwardRef((props, ref) => { onFocus={handleFocus} onBlur={handleBlur} onKeyDown={handleKeyDown} + onKeyUp={handleKeyUp} className={clsx( prefixCls, { diff --git a/tests/index.test.tsx b/tests/index.test.tsx index 8d104ab..59a5a26 100644 --- a/tests/index.test.tsx +++ b/tests/index.test.tsx @@ -40,6 +40,26 @@ describe('Input', () => { expect(onPressEnter).toHaveBeenCalled(); }); + it('should prevent long press of enter', () => { + const onKeyDown = jest.fn(); + const onPressEnter = jest.fn(); + const onKeyUp = jest.fn(); + const { container } = render( + , + ); + const inputEl = container.querySelector('input')!; + fireEvent.keyDown(inputEl, { key: 'Enter' }); + fireEvent.keyDown(inputEl, { key: 'Enter' }); + fireEvent.keyUp(inputEl, { key: 'Enter' }); + expect(onKeyDown).toBeCalledTimes(2); + expect(onPressEnter).toBeCalledTimes(1); + expect(onKeyUp).toBeCalledTimes(1); + }); + it('should trigger onChange', () => { const onChange = jest.fn(); const { container } = render();