Lev*_*dra 2 reactjs formik chakra-ui
问题是,由于某种原因,递增和递减按钮不会影响输入中的最终值,但是当您直接在输入中输入值时,该值会发生变化。
import { Box, Button, FormControl, FormErrorMessage, FormLabel, HStack, Input, useNumberInput } from '@chakra-ui/react';
import { Field, useField } from 'formik';
import React from 'react';
interface TextInputProps{
name: string;
label: string;
}
const CountInput: React.FC<TextInputProps> = ({ name, label}) => {
const [field, { error, touched }] = useField(name);
const {
getInputProps,
getIncrementButtonProps,
getDecrementButtonProps,
} = useNumberInput({
step: 1,
defaultValue: 1,
min: 1,
max: 10,
precision: 0,
})
const inc = getIncrementButtonProps();
const dec = getDecrementButtonProps();
const input = getInputProps({ ...field });
return (
<Field name={name}>
{({ form }: any) => {
return (
<FormControl isInvalid={form.errors[name] && form.touched[name]}>
<FormLabel htmlFor={name}>{label}</FormLabel>
{description && <Box mb={5}>{description}</Box>}
<HStack maxW="320px">
<Button {...dec}>-</Button>
<Input id={name} onChange={(val) => form.setFieldValue(field.name, val)} {...input} />
<Button {...inc}>+</Button>
</HStack>
<FormErrorMessage>{form.errors[name]}</FormErrorMessage>
</FormControl>
);
}}
</Field>
);
}
export default CountInput;
Run Code Online (Sandbox Code Playgroud)
我猜测问题在于将属性传播...field到getInputProps(),这又重置了该值。
小智 5
传播后传递onChange如下:useNumberInput...field
const [field, meta, helpers] = useField(name);
const { getInputProps, getIncrementButtonProps, getDecrementButtonProps } =
useNumberInput({
...field,
onChange: (valueAsString, valueAsNumber) => helpers.setValue(valueAsNumber),
});
Run Code Online (Sandbox Code Playgroud)
因为 的onChange参数useNumberInput期望
(method) UseCounterProps.onChange?(valueAsString: string, valueAsNumber: number): void
Run Code Online (Sandbox Code Playgroud)
而onChangeof fieldfromuseField有不同的签名。
| 归档时间: |
|
| 查看次数: |
1695 次 |
| 最近记录: |