如何使用 onSubmit 键入 Form 组件?

Six*_*ght 20 typescript reactjs typescript-typings

我有自己的Form组件,我想将它与Parent Component.

const Form: React.FC<any> = ({ children, handleFormSubmit }) => (
  <form onSubmit={handleFormSubmit}>{children}</form>
);
Run Code Online (Sandbox Code Playgroud)

Parent Component

const ParentComponent = () => {
...

const handleFormSubmit = (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    publishReview(review).then(() => setReview(initialReviewState));
  };

return (
 <Form onSubmit={handleFormSubmit}>
...
</Form>
)}
Run Code Online (Sandbox Code Playgroud)

我认为handleFormSubmit会从它的声明中获取类型const handleFormSubmit = (event: React.FormEvent<HTMLFormElement>)

但它没有

我试图构建一个接口,甚至使用一种any类型:

interface FormProps {
  handleFormSubmit: any
}
const Form: React.FC<FormProps>= ({ children, handleFormSubmit }) => (
  <form onSubmit={handleFormSubmit}>{children}</form>
);
Run Code Online (Sandbox Code Playgroud)

但它给出了以下错误:

const Form: React.FunctionComponent<FormProps>
Type '{ children: Element; onSubmit: (event: FormEvent<HTMLFormElement>) => void; }' is not assignable to type 'IntrinsicAttributes & FormProps & { children?: ReactNode; }'.
  Property 'onSubmit' does not exist on type 'IntrinsicAttributes & FormProps & { children?: ReactNode; }'.
Run Code Online (Sandbox Code Playgroud)

Bda*_*day 27

这对我有用。只是根据你的猜测猜测。谢谢!

handlePostForm = (e: React.FormEvent) => {
Run Code Online (Sandbox Code Playgroud)

  • 这种方法的一个问题是。它不会让你破坏 `e.target` 中的 props (4认同)

Ivo*_*Ivo 23

您需要指定表单元素的类型。假设在您的表单中您有一个带有 id 的输入yourInputName

<form onSubmit={handleSubmit}>
  <div>
    <label htmlFor="yourInputName">Username:</label>
    <input id="yourInputName" type="text" />
  </div>
  <button type="submit">Submit</button>
</form>
Run Code Online (Sandbox Code Playgroud)

在您的 中handleSubmit,您需要指定event.currentTarget. 表单标签具有 类型HTMLFormElement和 属性elements,属性是 类型HTMLFormControlsCollection,但我们可以覆盖它来告诉 TS 我们的输入是什么。创建一个扩展 的接口HTMLFormControlsCollection,指定字段的类型,然后使用自定义接口覆盖HTMLFormElement.

interface FormElements extends HTMLFormControlsCollection {
    yourInputName: HTMLInputElement
}

interface YourFormElement extends HTMLFormElement {
   readonly elements: FormElements
}
Run Code Online (Sandbox Code Playgroud)

然后将新类型传递给处理函数

const handleFormSubmit = (e: React.FormEvent<YourFormElement>) => {}
Run Code Online (Sandbox Code Playgroud)

您现在可以访问字段的值,打字稿将知道它是什么

const handleFormSubmit = (e: React.FormEvent<YourFormElement>) => {
    e.preventDefault();
    console.log(e.currentTarget.elements.yourInputName.value)
}
Run Code Online (Sandbox Code Playgroud)

如果您将鼠标悬停在 上value,TS 应向您显示一条消息,表明数据类型为HTMLInputElement.value: string,正如您在FormElements界面中指定的那样。


Eva*_*que 14

  const handleSubmit = (event: FormEvent<HTMLFormElement>) => {
Run Code Online (Sandbox Code Playgroud)