React中FormData的使用實(shí)例詳解
React中FormData的使用
export default function Signup() {
function handleSubmit(event) {
event.preventDefault();
const fd = new FormData(event.target);
console.log(fd.get("email"));
const acquisitionData = fd.getAll("acquisition");
const data = Object.fromEntries(fd);
data.acquisition = acquisitionData;
console.log(data);
}
return (
<form onSubmit={handleSubmit}>
<h2>Welcome on board!</h2>
<p>We just need a little bit of data from you to get you started ??</p>
<div className="control">
<label htmlFor="email">Email</label>
<input id="email" type="email" name="email" />
</div>
<div className="control-row">
<div className="control">
<label htmlFor="password">Password</label>
<input id="password" type="password" name="password" />
</div>
<div className="control">
<label htmlFor="confirm-password">Confirm Password</label>
<input
id="confirm-password"
type="password"
name="confirm-password"
/>
</div>
</div>
<hr />
<div className="control-row">
<div className="control">
<label htmlFor="first-name">First Name</label>
<input type="text" id="first-name" name="first-name" />
</div>
<div className="control">
<label htmlFor="last-name">Last Name</label>
<input type="text" id="last-name" name="last-name" />
</div>
</div>
<div className="control">
<label htmlFor="phone">What best describes your role?</label>
<select id="role" name="role">
<option value="student">Student</option>
<option value="teacher">Teacher</option>
<option value="employee">Employee</option>
<option value="founder">Founder</option>
<option value="other">Other</option>
</select>
</div>
<fieldset>
<legend>How did you find us?</legend>
<div className="control">
<input
type="checkbox"
id="google"
name="acquisition"
value="google"
/>
<label htmlFor="google">Google</label>
</div>
<div className="control">
<input
type="checkbox"
id="friend"
name="acquisition"
value="friend"
/>
<label htmlFor="friend">Referred by friend</label>
</div>
<div className="control">
<input type="checkbox" id="other" name="acquisition" value="other" />
<label htmlFor="other">Other</label>
</div>
</fieldset>
<div className="control">
<label htmlFor="terms-and-conditions">
<input type="checkbox" id="terms-and-conditions" name="terms" />I
agree to the terms and conditions
</label>
</div>
<p className="form-actions">
<button type="reset" className="button button-flat">
Reset
</button>
<button type="submit" className="button">
Sign up
</button>
</p>
</form>
);
}FormData 是一個(gè)強(qiáng)大的 API,用于處理表單數(shù)據(jù),特別是在需要將表單數(shù)據(jù)發(fā)送到服務(wù)器時(shí)非常有用。以下是對(duì) FormData 的詳細(xì)使用說明,包括如何創(chuàng)建、操作和使用它。
1. 創(chuàng)建 FormData 對(duì)象
從表單元素創(chuàng)建
可以通過將表單元素傳遞給 FormData 構(gòu)造函數(shù)來創(chuàng)建一個(gè) FormData 對(duì)象。這會(huì)自動(dòng)將表單中所有帶有 name 屬性的字段添加到 FormData 中。
const form = document.querySelector('form');
const formData = new FormData(form);手動(dòng)創(chuàng)建
也可以手動(dòng)創(chuàng)建一個(gè)空的 FormData 對(duì)象,然后逐步添加數(shù)據(jù)。
const formData = new FormData();
2. 添加數(shù)據(jù)到 FormData
append(key, value)
用于向 FormData 中添加一個(gè)鍵值對(duì)。
formData.append('username', 'john_doe');
formData.append('email', 'john@example.com');set(key, value)
與 append 類似,但如果鍵已經(jīng)存在,則會(huì)替換原有的值。
formData.set('username', 'john_doe'); // 添加
formData.set('username', 'jane_doe'); // 替換delete(key)
用于刪除指定的鍵值對(duì)。
formData.delete('username');3. 獲取 FormData 中的數(shù)據(jù)
get(key)
獲取指定鍵的值。
const username = formData.get('username');
console.log(username); // 輸出 'john_doe'getAll(key)
獲取指定鍵的所有值(如果一個(gè)鍵有多個(gè)值)。
formData.append('hobbies', 'reading');
formData.append('hobbies', 'coding');
const hobbies = formData.getAll('hobbies');
console.log(hobbies); // 輸出 ['reading', 'coding']has(key)
檢查 FormData 是否包含指定的鍵。
console.log(formData.has('username')); // 輸出 true 或 false4. 遍歷 FormData
forEach(callback)
遍歷 FormData 中的所有鍵值對(duì)。
formData.forEach((value, key) => {
console.log(`${key}: ${value}`);
});entries()
返回一個(gè)迭代器,可以用來遍歷所有鍵值對(duì)。
for (const [key, value] of formData.entries()) {
console.log(`${key}: ${value}`);
}keys() 和 values()
分別返回一個(gè)迭代器,用于遍歷所有鍵或所有值。
for (const key of formData.keys()) {
console.log(key);
}
for (const value of formData.values()) {
console.log(value);
}5. 將 FormData 轉(zhuǎn)換為其他格式
轉(zhuǎn)換為對(duì)象
可以將 FormData 轉(zhuǎn)換為普通的 JavaScript 對(duì)象。
const formDataObject = {};
formData.forEach((value, key) => {
formDataObject[key] = value;
});
console.log(formDataObject);轉(zhuǎn)換為 JSON
如果需要將 FormData 轉(zhuǎn)換為 JSON,可以先將其轉(zhuǎn)換為對(duì)象,然后再使用 JSON.stringify。
const formDataObject = Object.fromEntries(formData.entries()); const formDataJSON = JSON.stringify(formDataObject); console.log(formDataJSON);
6. 使用 FormData 提交表單
通過 fetch 發(fā)送數(shù)據(jù)
fetch API 支持直接發(fā)送 FormData 對(duì)象作為請(qǐng)求體。
fetch('https://example.com/api/submit', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));通過 XMLHttpRequest 發(fā)送數(shù)據(jù)
XMLHttpRequest 也支持直接發(fā)送 FormData。
const xhr = new XMLHttpRequest();
xhr.open('POST', 'https://example.com/api/submit');
xhr.send(formData);7. 文件上傳
FormData 特別適合處理文件上傳,因?yàn)樗梢暂p松地將文件添加到表單數(shù)據(jù)中。
const formData = new FormData();
formData.append('profile_picture', fileInput.files[0]); // fileInput 是文件輸入元素然后通過 fetch 或 XMLHttpRequest 發(fā)送數(shù)據(jù):
fetch('https://example.com/api/upload', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));8. 在 React 中使用 FormData
在 React 中,可以結(jié)合表單的 onSubmit 事件使用 FormData。
function MyForm() {
const handleSubmit = (e) => {
e.preventDefault();
const formData = new FormData(e.target);
// 處理表單數(shù)據(jù)
console.log(Object.fromEntries(formData.entries()));
};
return (
<form onSubmit={handleSubmit}>
<input type="text" name="username" />
<input type="email" name="email" />
<button type="submit">提交</button>
</form>
);
}總結(jié)
FormData 是一個(gè)非常靈活的工具,適用于處理表單數(shù)據(jù),特別是在需要發(fā)送文件或復(fù)雜表單數(shù)據(jù)時(shí)。它支持動(dòng)態(tài)添加、修改和刪除數(shù)據(jù),并且可以直接與 fetch 或 XMLHttpRequest 配合使用,方便地將數(shù)據(jù)發(fā)送到服務(wù)器。
到此這篇關(guān)于React中FormData的使用實(shí)例詳解的文章就介紹到這了,更多相關(guān)React FormData使用內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
解析React中useMemo與useCallback的區(qū)別
這篇文章主要介紹了React中useMemo與useCallback的區(qū)別,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-08-08
React如何使用錯(cuò)誤邊界(Error Boundaries)捕獲組件錯(cuò)誤
在 React 里,錯(cuò)誤邊界就像是一個(gè)“小衛(wèi)士”,專門負(fù)責(zé)在組件出現(xiàn)錯(cuò)誤時(shí)挺身而出,避免整個(gè)應(yīng)用因?yàn)橐粋€(gè)小錯(cuò)誤就崩潰掉,下面小編就來為大家介紹一下如何利用它捕獲組件錯(cuò)誤吧2025-03-03
React?+?Typescript領(lǐng)域初學(xué)者的常見問題和技巧(最新)
這篇文章主要介紹了React?+?Typescript領(lǐng)域初學(xué)者的常見問題和技巧,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-06-06
React使用PropTypes實(shí)現(xiàn)類型檢查功能
這篇文章主要介紹了React高級(jí)指引中使用PropTypes實(shí)現(xiàn)類型檢查功能的方法,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧2023-02-02
React中使用TS完成父組件調(diào)用子組件的操作方法
由于在項(xiàng)目開發(fā)過程中,我們往往時(shí)需要調(diào)用子組件中的方法,這篇文章主要介紹了React中使用TS完成父組件調(diào)用子組件,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-07-07
React-Router(V6)的權(quán)限控制實(shí)現(xiàn)示例
本文主要介紹了React-Router(V6)的權(quán)限控制實(shí)現(xiàn)示例,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-05-05

