Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 12 additions & 2 deletions src/Input.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ const Input = forwardRef<InputRef, InputProps>((props, ref) => {
onBlur,
onPressEnter,
onKeyDown,
onKeyUp,
prefixCls = 'rc-input',
disabled,
htmlSize,
Expand All @@ -42,6 +43,7 @@ const Input = forwardRef<InputRef, InputProps>((props, ref) => {

const [focused, setFocused] = useState<boolean>(false);
const compositionRef = useRef(false);
const keyLockRef = useRef(false);

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

const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
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<HTMLInputElement>) => {
onKeyUp?.(e);
if (e.key === 'Enter') {
keyLockRef.current = false;
}
};

const handleFocus: React.FocusEventHandler<HTMLInputElement> = (e) => {
Expand Down Expand Up @@ -215,6 +224,7 @@ const Input = forwardRef<InputRef, InputProps>((props, ref) => {
onFocus={handleFocus}
onBlur={handleBlur}
onKeyDown={handleKeyDown}
onKeyUp={handleKeyUp}
className={clsx(
prefixCls,
{
Expand Down
20 changes: 20 additions & 0 deletions tests/index.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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(
<Input
onKeyDown={onKeyDown}
onPressEnter={onPressEnter}
onKeyUp={onKeyUp}
/>,
);
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(<Input onChange={onChange} />);
Expand Down