最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Giving HTML form to FormData through event.target is throwing Argument of type 'EventTarget' is not

programmeradmin0浏览0评论

I'm trying to get the values from a form into FormData:

  const handleSubmit = (e: FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    const formData = new FormData(e.target as HTMLFormElement);
    const value = formData.get('origin') ? 'open' : 'on';
    updateResizingOptionsQuery.mutate({ value });
  };

Since React sends SynteticEvents, the interface of e.target does not fit the FormData constructor. In the example, I'm casting the type which is not ideal. What would be a better version of that code?

Without casting this lint error is thrown:

Argument of type 'EventTarget' is not assignable to parameter of type 'HTMLFormElement'. Type 'EventTarget' is missing the following properties from type 'HTMLFormElement': acceptCharset, action, autoplete, elements, and 297 more.

I'm trying to get the values from a form into FormData:

  const handleSubmit = (e: FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    const formData = new FormData(e.target as HTMLFormElement);
    const value = formData.get('origin') ? 'open' : 'on';
    updateResizingOptionsQuery.mutate({ value });
  };

Since React sends SynteticEvents, the interface of e.target does not fit the FormData constructor. In the example, I'm casting the type which is not ideal. What would be a better version of that code?

Without casting this lint error is thrown:

Argument of type 'EventTarget' is not assignable to parameter of type 'HTMLFormElement'. Type 'EventTarget' is missing the following properties from type 'HTMLFormElement': acceptCharset, action, autoplete, elements, and 297 more.

Share Improve this question edited Jan 30, 2023 at 22:18 Youssouf Oumar 46.3k16 gold badges101 silver badges104 bronze badges asked Jan 30, 2023 at 13:59 Xen_marXen_mar 9,75219 gold badges59 silver badges103 bronze badges 0
Add a ment  | 

1 Answer 1

Reset to default 11

Using e.currentTarget instead of e.target works. Because currentTarget always refers to the root event listener element, TypeScript knows it's the <form>:

import { FormEvent } from "react";
export default function App() {
const handleSubmit = (e: FormEvent<HTMLFormElement>) => {
  e.preventDefault();
  const formData = new FormData(e.currentTarget);
  const value = formData.get("origin") ? "open" : "on";
  updateResizingOptionsQuery.mutate({ value });
};
  return (
    <div className="App">
      <form onSubmit={handleSubmit}></form>
    </div>
  );
}

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论