React中FormData的使用实例详解
作者:zwjapple
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 是一个强大的 API,用于处理表单数据,特别是在需要将表单数据发送到服务器时非常有用。以下是对 FormData 的详细使用说明,包括如何创建、操作和使用它。
1. 创建 FormData 对象
从表单元素创建
可以通过将表单元素传递给 FormData 构造函数来创建一个 FormData 对象。这会自动将表单中所有带有 name 属性的字段添加到 FormData 中。
const form = document.querySelector('form');
const formData = new FormData(form);手动创建
也可以手动创建一个空的 FormData 对象,然后逐步添加数据。
const formData = new FormData();
2. 添加数据到 FormData
append(key, value)
用于向 FormData 中添加一个键值对。
formData.append('username', 'john_doe');
formData.append('email', 'john@example.com');set(key, value)
与 append 类似,但如果键已经存在,则会替换原有的值。
formData.set('username', 'john_doe'); // 添加
formData.set('username', 'jane_doe'); // 替换delete(key)
用于删除指定的键值对。
formData.delete('username');3. 获取 FormData 中的数据
get(key)
获取指定键的值。
const username = formData.get('username');
console.log(username); // 输出 'john_doe'getAll(key)
获取指定键的所有值(如果一个键有多个值)。
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 中的所有键值对。
formData.forEach((value, key) => {
console.log(`${key}: ${value}`);
});entries()
返回一个迭代器,可以用来遍历所有键值对。
for (const [key, value] of formData.entries()) {
console.log(`${key}: ${value}`);
}keys() 和 values()
分别返回一个迭代器,用于遍历所有键或所有值。
for (const key of formData.keys()) {
console.log(key);
}
for (const value of formData.values()) {
console.log(value);
}5. 将 FormData 转换为其他格式
转换为对象
可以将 FormData 转换为普通的 JavaScript 对象。
const formDataObject = {};
formData.forEach((value, key) => {
formDataObject[key] = value;
});
console.log(formDataObject);转换为 JSON
如果需要将 FormData 转换为 JSON,可以先将其转换为对象,然后再使用 JSON.stringify。
const formDataObject = Object.fromEntries(formData.entries()); const formDataJSON = JSON.stringify(formDataObject); console.log(formDataJSON);
6. 使用 FormData 提交表单
通过 fetch 发送数据
fetch API 支持直接发送 FormData 对象作为请求体。
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 发送数据
XMLHttpRequest 也支持直接发送 FormData。
const xhr = new XMLHttpRequest();
xhr.open('POST', 'https://example.com/api/submit');
xhr.send(formData);7. 文件上传
FormData 特别适合处理文件上传,因为它可以轻松地将文件添加到表单数据中。
const formData = new FormData();
formData.append('profile_picture', fileInput.files[0]); // fileInput 是文件输入元素然后通过 fetch 或 XMLHttpRequest 发送数据:
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 中,可以结合表单的 onSubmit 事件使用 FormData。
function MyForm() {
const handleSubmit = (e) => {
e.preventDefault();
const formData = new FormData(e.target);
// 处理表单数据
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>
);
}总结
FormData 是一个非常灵活的工具,适用于处理表单数据,特别是在需要发送文件或复杂表单数据时。它支持动态添加、修改和删除数据,并且可以直接与 fetch 或 XMLHttpRequest 配合使用,方便地将数据发送到服务器。
到此这篇关于React中FormData的使用实例详解的文章就介绍到这了,更多相关React FormData使用内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
