我正在使用反应钩表格。 我正在尝试使用该库的implemnet购物车,但遇到了麻烦 获取数字值。 输入标签,使用时 name =“ count” 总是返回字符串值,甚至设置为 type =“ number” 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>
</>
)
}
答案 0 :(得分:1)
在类型为数字的输入上发生onChange
事件将为您提供与输入的数字相对应的字符串。那是浏览器的行为。尝试更新值时,需要将值解析为整数,然后更新
const onIncrease = () => count < 999 && setValue('count',parseInt(count) + 1);
const onDecrease = () => count > 1 && setValue('count',parseInt(count) - 1);