标题重写为:"react-hook-form中的Hook调用无效"
<p>我对react hook form还不熟悉,所以可能是一个简单的问题。我刚刚发现Controller无法将value作为数字使用。这让我很烦恼,但最终我在github的问题#8068中找到了解决方案,描述如下:设置一个onChange函数,像这样:</p>
<pre class="brush:php;toolbar:false;"><Controller
- rules={{ valueAsNumber: true }}
render={({ field }) => (
<input
- onChange={field.onChange}
+ onChange={(event) => field.onChange(+event.target.value)}
type="number"
/>
)}
/></pre>
<p>所以我稍微修改了一下,得到了以下代码:</p>
<pre class="brush:php;toolbar:false;">import React, { ChangeEvent } from 'react'
import { Controller } from 'react-hook-form'
import { getPlaceholder } from './getPlaceholder'
import { IInput } from './types'
const NumberInput: React.FC<IInput> = ({ control, name, ...props }) => {
const placeholder = getPlaceholder({ type: "number" });
const numericalOnChange = (event: ChangeEvent<HTMLInputElement>) => {
if (event.target.value === '') return null;
return +event.target.value;
}
return (
<Controller
control={control}
name={name}
render={({ field: { onChange, ...field } }) => (
<input
{...props}
{...field}
type="number"
placeholder={placeholder}
onChange={(event) => {
const value = numericalOnChange(event)
onChange(value)
}}
className="h-[20px] pl-[4px] py-[8px] bg-transparent border-b
border-b-[#646464] focus:border-b-[#3898EC] text-[13px]
text-[#F00] placeholder-[#646464] outline-none m-1 w-full"
/>
)}
/>
)
}
export default NumberInput</pre>
<p>理论上应该可以工作,但实际上会提供一个Invalid Hook Call Error。</p>