Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: fix error when pass disabled and press enter. #81

Merged
merged 5 commits into from
Nov 29, 2024
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
6 changes: 6 additions & 0 deletions src/Input.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,9 @@ const Input = forwardRef<InputRef, InputProps>((props, ref) => {
}));

useEffect(() => {
if (keyLockRef.current) {
keyLockRef.current = false;
}
setFocused((prev) => (prev && disabled ? false : prev));
}, [disabled]);

Expand Down Expand Up @@ -176,6 +179,9 @@ const Input = forwardRef<InputRef, InputProps>((props, ref) => {
};

const handleBlur: React.FocusEventHandler<HTMLInputElement> = (e) => {
if (keyLockRef.current) {
keyLockRef.current = false;
}
setFocused(false);
onBlur?.(e);
};
Expand Down
28 changes: 28 additions & 0 deletions tests/index.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,34 @@ describe('Input', () => {
expect(onKeyUp).toBeCalledTimes(1);
});

it('should trigger onPressEnter after trigger onBlur', () => {
const onPressEnter = jest.fn();
const onBlur = jest.fn();
const { container } = render(
<Input onPressEnter={onPressEnter} onBlur={onBlur} />,
);
const inputEl = container.querySelector('input')!;
fireEvent.keyDown(inputEl, { key: 'Enter' });
fireEvent.blur(inputEl);
fireEvent.keyDown(inputEl, { key: 'Enter' });
expect(onBlur).toBeCalled();
expect(onPressEnter).toBeCalledTimes(2);
});

it('should trigger onPressEnter after disabled', () => {
const onPressEnter = jest.fn();
const { container, rerender } = render(
<Input onPressEnter={onPressEnter} />,
);
const inputEl = container.querySelector('input')!;
expect(inputEl.disabled).toBe(false);
fireEvent.keyDown(inputEl, { key: 'Enter' });
rerender(<Input onPressEnter={onPressEnter} disabled={true} />);
expect(inputEl.disabled).toBe(true);
fireEvent.keyDown(inputEl, { key: 'Enter' });
expect(onPressEnter).toBeCalledTimes(2);
});

it('should trigger onChange', () => {
const onChange = jest.fn();
const { container } = render(<Input onChange={onChange} />);
Expand Down
Loading