使用 Formik 在 Chackra 中使用数字输入钩子

问题描述

问题是由于某种原因,递增和递减按钮不影响输入中的最终值,但是当您直接在输入中输入值时,该值会发生变化。

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;

我猜问题在于将属性点差 ...field 传递给 getInputProps(),这又会重置值。

解决方法

onChange 传播后将 useNumberInput 传递给 ...field,如下所示:

const [field,meta,helpers] = useField(name);
const { getInputProps,getIncrementButtonProps,getDecrementButtonProps } =
useNumberInput({
  ...field,onChange: (valueAsString,valueAsNumber) => helpers.setValue(valueAsNumber),});

因为 onChangeuseNumberInput 参数需要

(method) UseCounterProps.onChange?(valueAsString: string,valueAsNumber: number): void

而来自 onChangefielduseField 具有不同的签名。

,

字段的内容是什么?

我也在尝试在 Chakra 中使用 useNumberInput 钩子,get input props 只接受一些值,它们在这里

export declare function useNumberInput(props?: UseNumberInputProps): {
    value: React.ReactText;
    valueAsNumber: number;
    isFocused: boolean;
    isDisabled: boolean | undefined;
    isReadOnly: boolean | undefined;
    getIncrementButtonProps: PropGetter<any,{}>;
    getDecrementButtonProps: PropGetter<any,{}>;
    getInputProps: PropGetter<any,{}>;
    htmlProps: {
        defaultValue?: string | number | undefined;
        value?: string | number | undefined;
    };
};

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...