Skip to content

Commit

Permalink
fix(InputNumber): work with increment/decrement buttons
Browse files Browse the repository at this point in the history
  • Loading branch information
SevenOutman committed Apr 13, 2022
1 parent 5780771 commit 4ae9880
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 1 deletion.
11 changes: 10 additions & 1 deletion src/InputNumber.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,17 @@ export function InputNumber({
return (
<RsInputNumber
{...field}
// Don't use field.onChange here
// because event can be other type than change
// e.g. MouseEvent from stepUp/stepDown button
// KeyboardEvent from ArrowUp/ArrowDown keys
onChange={(newValue: any, event) => {
field.onChange(event);
const parsed = parseFloat(newValue);

// Handle target.value as text
// copied from field.onChange
// see https://github.com/jaredpalmer/formik/blob/e677bea8181f40e6762fc7e7fb009122384500c6/packages/formik/src/Formik.tsx#L630
form.setFieldValue(field.name, isNaN(parsed) ? newValue : parsed);
onChange?.(newValue, event);
}}
{...props}
Expand Down
29 changes: 29 additions & 0 deletions src/__tests__/InputNumber.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -32,3 +32,32 @@ test("适配 formik", async () => {
expect(formikRef.current?.values).toHaveProperty("age", 29);
});
});

test("点击增加/减少按钮有效", async () => {
const formikRef = React.createRef<FormikProps<{ age: number }>>();
const { container } = render(
<Formik
innerRef={formikRef}
initialValues={{
age: 18,
}}
onSubmit={_.noop}
>
<Form>
<Field name="age" component={InputNumber} />
</Form>
</Formik>
);

userEvent.click(container.querySelector(".rs-input-number-touchspin-up")!);

await waitFor(() => {
expect(formikRef.current?.values.age).toBe(19);
});

userEvent.click(container.querySelector(".rs-input-number-touchspin-down")!);

await waitFor(() => {
expect(formikRef.current?.values.age).toBe(18);
});
});

0 comments on commit 4ae9880

Please sign in to comment.