react-hook-form 7自定义输入,空值



我有以下自定义输入组件:

export type InputProps = {
error?: string
} & InputHTMLAttributes<HTMLInputElement>
export const Input: FunctionComponent<InputProps> = ({ error, ...props }) => (
<input {...props} />
)

使用

<form onSubmit={handleSubmit(onSubmit)}>
<Input placeholder="https://example.com" error={errors.url?.message} {...register('url')} />
<input type="submit" />
</form>

当我尝试使用它时,我得到一个验证错误,因为URL是空的(空字符串),我试图调试,函数注册只返回{name: "url"},这对我来说似乎很可疑。

我做错了什么?

编辑我在控制台上看到这个

Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?
Check the render method of `Home`.
at Input (webpack-internal:///./components/input.tsx:10:11)
at form
at div
at div
at Home (webpack-internal:///./pages/index.tsx:17:90)
at App (webpack-internal:///./pages/_app.tsx:11:11)
at Hydrate (webpack-internal:///./node_modules/@tanstack/react-query/build/lib/Hydrate.mjs:30:3)
at QueryClientProvider (webpack-internal:///./node_modules/@tanstack/react-query/build/lib/QueryClientProvider.mjs:47:3)
at TRPCProvider (webpack-internal:///./node_modules/@trpc/react-query/dist/createHooksInternal-2bef4843.mjs:158:17)
at WithTRPC (webpack-internal:///./node_modules/@trpc/next/dist/index.mjs:44:83)
at PathnameContextProviderAdapter (webpack-internal:///./node_modules/next/dist/shared/lib/router/adapters.js:62:11)
at ErrorBoundary (webpack-internal:///./node_modules/next/dist/compiled/@next/react-dev-overlay/dist/client.js:2:3325)
at ReactDevOverlay (webpack-internal:///./node_modules/next/dist/compiled/@next/react-dev-overlay/dist/client.js:2:6707)
at Container (webpack-internal:///./node_modules/next/dist/client/index.js:60:1)
at AppContainer (webpack-internal:///./node_modules/next/dist/client/index.js:173:11)
at Root (webpack-internal:///./node_modules/next/dist/client/index.js:346:11)

错误提示您试图通过useRef来引用功能组件本身。

为了提供对功能组件的引用,它应该通过forwardRef来实现。

除了不能看到什么作为代码实现在你的端,错误还告诉你看看渲染函数'Home' '组件,因为您在'./components/input.tsx下使用了上述共享的输入组件的引用。"。

如果你提供的话,我可以添加如何包装你的组件或对沙箱进行编辑,但是,你更有可能得到一个不遵循React命名约定的错误。如React文档中所述;

组件名称始终以大写字母

开头**这意味着根据组件名称Input,您应该将您的文件命名为Input.tsx

最新更新