我有一個應該將檔案(影像)上傳到 NextJs API 路由的表單。我嘗試使用對表單的參考來檢索表單值。但是,當我嘗試訪問 onSubmit 函式中的表單時,ref 仍然為空。我知道 refs 在第一次渲染時可以為 null,但我認為在提交表單時,應該決議 ref。
這是表格的樣子:
<form ref={formRef} onSubmit={onFormSubmit}>
<label htmlFor="image">Image:</label>
<input id="image" accept="image/*" multiple={false} onChange={onImageChange} name="image" type="file" required />
<button type="submit">Upload</button>
</form>
這是(功能)組件的其余部分的樣子:
const UploadImageModal = (): JSX.Element => {
const formRef = useRef<HTMLFormElement>(null)
const onFormSubmit = async (event: SubmitEvent) => {
event.preventDefault()
console.log(formRef.current) //Shows null
const data = new FormData(formRef.current)
const res = await fetch('/api/upload-image', {
method: 'POST',
body: data
})
}
return (/* The component including the form */)
}
我正在使用 TypeScript,但是我認為這無關緊要,因為 TypeScript 在運行時沒有影響。我遺漏了任何我認為與這個問題無關的東西,比如樣式和不接觸表單的其余組件。
API 路由已經使用 Postman 進行了測驗,并且按預期作業。如果有一種方法可以直接從 SubmitEvent 獲取表單資料,那也是一個很好的解決方案。我認為 formdata 會通過該事件公開,但它并沒有讓我到任何地方。
感謝任何花時間幫助我的人!
uj5u.com熱心網友回復:
您可以通過以下方式獲取表單 DOM 參考
const data = new FormData(event.target)
[資訊] 您正在使用打字稿,因此處理程式的型別應該是
const onFormSubmit: FormEventHandler<HTMLFormElement > = async (event) => {
uj5u.com熱心網友回復:
我在下面附上了作業代碼和 Codesandbox。 https://codesandbox.io/s/react-functional-component-form-usage-with-typescript-16ghf?file=/src/App.tsx
import "./styles.css";
import { SyntheticEvent, useRef } from "react";
const UploadImageModal = (): JSX.Element => {
const formRef = useRef() as React.MutableRefObject<HTMLFormElement>;
const onFormSubmit = async (event: SyntheticEvent) => {
event.preventDefault();
console.log(formRef); //Shows null
const data = new FormData(formRef.current);
const res = await fetch("/api/upload-image", {
method: "POST",
body: data
});
};
return (
<form ref={formRef} onSubmit={onFormSubmit}>
<label htmlFor="image">Image:</label>
<input
id="image"
accept="image/*"
multiple={false}
name="image"
type="file"
required
/>
<button type="submit">Upload</button>
</form>
);
};
export default function App() {
return (
<div className="App">
<UploadImageModal />
</div>
);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/391066.html
