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

问题描述 投票:0回答:1

我用的是 钩形反应我想用这个库来实现购物车,但在获取数字值时遇到了困难。name="count" 始终返回字符串值,即使设置 type="数字" 使用时 getValues("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>
    </>
  )
}
reactjs react-hook-form
1个回答
1
投票

一个 onChange 事件会给你输入的数字对应的字符串。这是浏览器的行为。当你试图更新数值时,你需要将数值解析为一个整数,然后再更新。

  const onIncrease = () => count < 999 && setValue('count',parseInt(count) + 1);
  const onDecrease = () => count > 1 && setValue('count',parseInt(count) - 1);
© www.soinside.com 2019 - 2024. All rights reserved.