From e9d6848c41521548992608559019b1d6820f6022 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B6=E6=9E=AB?= <7971419+crazyair@users.noreply.github.com> Date: Thu, 18 Jul 2024 11:52:03 +0800 Subject: [PATCH] feat: Prevent long press of enter (#72) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat: Prevent long press of enter * feat: test * feat: 优化 if * feat: keyLockRef --- src/Input.tsx | 14 ++++++++++++-- tests/index.test.tsx | 20 ++++++++++++++++++++ 2 files changed, 32 insertions(+), 2 deletions(-) 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();