如何在我的 React 应用程序中正确编写 FormData?

tyr*_*yry 6 javascript reactjs

我在我的应用程序中添加了一个表单。当我将表单数据发送到我的本地服务器时,我创建了一个带有标题的图像。当我附加图像时,我应该使用input type="file". 另外,我应该在我的应用程序中使用 FormData。

但是当我编写组件时,我'formElem' is not defined在代码中注释的两行中出现错误。我如何解决它?

这是我的组件代码:

const AddImage = (props) => {
     formElem.onsubmit = async (e) => {         // ERROR THERE
       e.preventDefault();

          try {
              const response = await api(`${imageRoute}`, {
                  method:'POST',
                  body: new FormData(formElem),    // ERROR THERE
              }); 

          } catch(e) { 
              console.error(e);
          }   
    };

   return (

    <div className="formImage">

       <form id="formElem">
          <input type="text" name="name" value=""/>
          <input type="text" name="surname" value=""/>
          <input type="file" name="picture" accept="image/*"/>

        <div className="formButtonImage">
          <button type="submit">Add</button>
        </div>

       </form>
   </div>
   );
};
Run Code Online (Sandbox Code Playgroud)

Láď*_*nek 4

您的代码中有很多问题,但这应该可以解决大多数问题:

import React, { useRef } from "react";

const AddImage = (props) => {
  const formRef = useRef();

  const handleSubmit = async (event) => {
    event.preventDefault();
    const data = new FormData(formRef.current);
    // Let's assume that api and imageRoute SOMEHOW exists
    try {
      const response = await api(imageRoute, {
        method: 'POST',
        body: data,    // ERROR THERE
      }); 
    } catch(e) { 
      console.error(e);
    }  
  };

  return (
    <div className="formImage">
      <form onSubmit={handleSubmit} ref={formRef}>
        <input type="text" name="name" />
        <input type="text" name="surname" />
        <input type="file" name="picture" accept="image/*" />

        <div className="formButtonImage">
          <button type="submit">Add</button>
        </div>
      </form>
    </div>
  );
}
Run Code Online (Sandbox Code Playgroud)

确保value=""从表单元素中删除,否则 React 会将它们视为受控元素,并且您将无法实际写入它们。