Skip to content

Commit e9d6848

Browse files
authored
feat: Prevent long press of enter (#72)
* feat: Prevent long press of enter * feat: test * feat: 优化 if * feat: keyLockRef
1 parent 31ebcec commit e9d6848

File tree

2 files changed

+32
-2
lines changed

2 files changed

+32
-2
lines changed

src/Input.tsx

+12-2
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ const Input = forwardRef<InputRef, InputProps>((props, ref) => {
2323
onBlur,
2424
onPressEnter,
2525
onKeyDown,
26+
onKeyUp,
2627
prefixCls = 'rc-input',
2728
disabled,
2829
htmlSize,
@@ -42,6 +43,7 @@ const Input = forwardRef<InputRef, InputProps>((props, ref) => {
4243

4344
const [focused, setFocused] = useState<boolean>(false);
4445
const compositionRef = useRef(false);
46+
const keyLockRef = useRef(false);
4547

4648
const inputRef = useRef<HTMLInputElement>(null);
4749
const holderRef = useRef<HolderRef>(null);
@@ -155,10 +157,17 @@ const Input = forwardRef<InputRef, InputProps>((props, ref) => {
155157
};
156158

157159
const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
158-
if (onPressEnter && e.key === 'Enter') {
160+
onKeyDown?.(e);
161+
if (onPressEnter && e.key === 'Enter' && !keyLockRef.current) {
162+
keyLockRef.current = true;
159163
onPressEnter(e);
160164
}
161-
onKeyDown?.(e);
165+
};
166+
const handleKeyUp = (e: React.KeyboardEvent<HTMLInputElement>) => {
167+
onKeyUp?.(e);
168+
if (e.key === 'Enter') {
169+
keyLockRef.current = false;
170+
}
162171
};
163172

164173
const handleFocus: React.FocusEventHandler<HTMLInputElement> = (e) => {
@@ -215,6 +224,7 @@ const Input = forwardRef<InputRef, InputProps>((props, ref) => {
215224
onFocus={handleFocus}
216225
onBlur={handleBlur}
217226
onKeyDown={handleKeyDown}
227+
onKeyUp={handleKeyUp}
218228
className={clsx(
219229
prefixCls,
220230
{

tests/index.test.tsx

+20
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,26 @@ describe('Input', () => {
4040
expect(onPressEnter).toHaveBeenCalled();
4141
});
4242

43+
it('should prevent long press of enter', () => {
44+
const onKeyDown = jest.fn();
45+
const onPressEnter = jest.fn();
46+
const onKeyUp = jest.fn();
47+
const { container } = render(
48+
<Input
49+
onKeyDown={onKeyDown}
50+
onPressEnter={onPressEnter}
51+
onKeyUp={onKeyUp}
52+
/>,
53+
);
54+
const inputEl = container.querySelector('input')!;
55+
fireEvent.keyDown(inputEl, { key: 'Enter' });
56+
fireEvent.keyDown(inputEl, { key: 'Enter' });
57+
fireEvent.keyUp(inputEl, { key: 'Enter' });
58+
expect(onKeyDown).toBeCalledTimes(2);
59+
expect(onPressEnter).toBeCalledTimes(1);
60+
expect(onKeyUp).toBeCalledTimes(1);
61+
});
62+
4363
it('should trigger onChange', () => {
4464
const onChange = jest.fn();
4565
const { container } = render(<Input onChange={onChange} />);

0 commit comments

Comments
 (0)