我在我的应用程序中添加了一个表单。当我将表单数据发送到我的本地服务器时,我创建了一个带有标题的图像。当我附加图像时,我应该使用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)