react-hook-form,总是返回字符串类型值

dan*_*nte 14 reactjs react-hook-form

我正在使用react-hook-form。我正在尝试使用这个库实现购物车,但在获取数值方面遇到了困难。使用 getValues("count")时,即使设置type="number", name="count"始终返回字符串值的输入标记。

对于name="count"的字符串值,我的自定义函数增量无法按预期工作。当我单击 + 按钮时,它返回并添加了字符串。

import React, { FC, useEffect } from 'react';
import * as Styled from './style';
import { useForm, ErrorMessage} from 'react-hook-form';
import { ItemCountForm  } from 'src/models/item-count'; 
export const CountForm:FC<{
  partialData : Omit<ItemCountForm,'count'>
}> = ({
  partialData
}) => {

  const { register, handleSubmit, errors,getValues, setValue } = useForm<{count:number}>({
    defaultValues:{
      count: 1}
  });

  const onSubmit = async(data: {count: number}) => { 
    console.log('submitted');
    const formData: ItemCountForm = {
      id: partialData.id,
      name: partialData.name,
      count: data.count, 
      price: partialData.price * data.count
    }
    console.log(formData);

  }
  const count = getValues('count'); 
  const onIncrease = () => count < 999 && setValue('count',Number(count) + 1);
  const onDecrease = () => count > 1 && setValue('count',count - 1);
  return(
    <>
      <form onSubmit={handleSubmit(onSubmit)}>
        <input type="number" name="count"  ref={register({
          min:{
            value:1,
            message: "you need at least 1"
          },
          max: {
            value: 999,
            message: "you can have at most 999"
          }
        })}/>
        <ErrorMessage 
          errors={errors} 
          name={"count"} 
          as={<Styled.ErrorText/>}
        />
        <button onClick={onIncrease}>+</button>
        <button onClick={onDecrease}>-</button>
        <button type="submit">Add Cart</button>
      </form>
    </>
  )
}
Run Code Online (Sandbox Code Playgroud)

小智 24

也许晚了几年,但让我们把这个问题留给下一个开发人员来解决这个问题。

react-hook-form v 7valueAsNumber在选项对象上有一个键,您可以作为寄存器的第二个参数传递:

{...register('age', {valueAsNumber: true})}
Run Code Online (Sandbox Code Playgroud)

https://react-hook-form.com/api/useform/register

  • 我希望将接口传递给 useForm 应该足以保留对象的类型! (2认同)

Shu*_*tri 7

数字类型输入上的事件onChange将为您提供与输入的数字相对应的字符串。这是浏览器的行为。当您尝试更新该值时,您需要将该值解析为整数,然后更新

  const onIncrease = () => count < 999 && setValue('count',parseInt(count) + 1);
  const onDecrease = () => count > 1 && setValue('count',parseInt(count) - 1);
Run Code Online (Sandbox Code Playgroud)