我正在通过react-hook-form软件包的验证制作一个简单的表格。这种形式的字段是重用组件。当我使用react-hook-form的钩子时,将其表示为
const { register, errors, handleSubmit } = useForm<IFormDataSearchMovie>()
在编写onSubmit时,输入的参数类型无法识别,并突出显示:
Binding element 'title' implicitly has an 'any' type.
表单的组件:
import React, { FunctionComponent } from 'react';
import { useForm } from 'react-hook-form';
import { TextField } from '../TextField';
import { IFormDataSearchMovie } from '../../types';
export const ListOfMovies: FunctionComponent = () => {
const { register, errors, handleSubmit } = useForm<IFormDataSearchMovie>();
const onSubmit = ({ title }) => {
console.log(title);
};
return (
<div className='ListOfMovies'>
<h2>Lista de películas</h2>
<form onSubmit={handleSubmit(onSubmit)}>
<TextField
type='text'
placeholder='Introduce el nombre de la pelicula'
name='title'
register={register({ required: true })}
/>
</form>
</div>
);
};
TextField属性register
显示以下错误:
Type '(ref: HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement | (HTMLSelectElement & HTMLInputElement) | ... 12 more ... | null) => void' is not assignable to type '() => any'.ts(2322)
types.ts(17, 5): The expected type comes from property 'register' which is declared here on type 'IntrinsicAttributes & ITextFieldProps'
文本字段组件:
import React from 'react';
import { ITextFieldProps } from '../../types';
export const TextField = ({
type,
placeholder,
name,
register,
}: ITextFieldProps) => {
return (
<input
type={type}
placeholder={placeholder}
name={name}
ref={register}
/>
);
};
接口:
export interface ITextFieldProps {
type: string,
placeholder: string,
name: string,
register(): any,
}
export interface IFormDataSearchMovie {
title: string
}