Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 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
13 changes: 12 additions & 1 deletion 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 enterRef = useRef(false);

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

const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
onKeyDown?.(e);
if (onPressEnter && e.key === 'Enter') {
if (enterRef.current) return;
Comment thread
crazyair marked this conversation as resolved.
Outdated
enterRef.current = true;
onPressEnter(e);
}
onKeyDown?.(e);
};
const handleKeyUp = (e: React.KeyboardEvent<HTMLInputElement>) => {
onKeyUp?.(e);
if (e.key === 'Enter') {
Comment thread
crazyair marked this conversation as resolved.
enterRef.current = false;
}
};

const handleFocus: React.FocusEventHandler<HTMLInputElement> = (e) => {
Expand Down Expand Up @@ -215,6 +225,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