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ì)使用說(shuō)明,包括如何創(chuàng)建、操作和使用它。
1. 創(chuàng)建 FormData 對(duì)象
從表單元素創(chuàng)建
可以通過(guò)將表單元素傳遞給 FormData 構(gòu)造函數(shù)來(lái)創(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è)迭代器,可以用來(lái)遍歷所有鍵值對(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 提交表單
通過(guò) 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));通過(guò) 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 是文件輸入元素然后通過(guò) 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中使用collections時(shí)key的重要性詳解
這篇文章主要給大家介紹了關(guān)于在React.js中使用collections時(shí)key的重要性,注意:一定不能不能忘了key,文中通過(guò)示例代碼介紹的非常詳細(xì),需要的朋友可以參考借鑒,下面跟著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧。2017-08-08
React Native使用Modal自定義分享界面的示例代碼
本篇文章主要介紹了React Native使用Modal自定義分享界面的示例代碼,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-10-10
React class和function的區(qū)別小結(jié)
Class組件和Function組件是React中創(chuàng)建組件的兩種主要方式,本文主要介紹了React class和function的區(qū)別小結(jié),具有一定的參考價(jià)值,感興趣的可以了解一下2023-10-10
react-native?父函數(shù)組件調(diào)用類子組件的方法(實(shí)例詳解)
這篇文章主要介紹了react-native?父函數(shù)組件調(diào)用類子組件的方法,通過(guò)詳細(xì)步驟介紹了React 函數(shù)式組件之父組件調(diào)用子組件的方法,代碼簡(jiǎn)單易懂,對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-09-09
字節(jié)封裝React組件手機(jī)號(hào)自動(dòng)校驗(yàn)格式FormItem
這篇文章主要為大家介紹了字節(jié)封裝React組件手機(jī)號(hào)自動(dòng)校驗(yàn)格式FormItem,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-08-08
封裝一個(gè)最簡(jiǎn)單ErrorBoundary組件處理react異常
這篇文章主要介紹了一個(gè)處理react異常的ErrorBoundary組件,簡(jiǎn)單實(shí)用,代碼詳細(xì),對(duì)這個(gè)組件感興趣的朋友可以參考下2021-04-04

