1

問題は、何らかの理由で、インクリメント ボタンとデクリメント ボタンが入力の最終値に影響しないのに、入力に値を直接入力すると値が変化することです。

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;

私は問題がプロパティを渡すことであると推測しています スプレッド...fieldgetInputProps()、値がリセットされます。

4

2 に答える 2