React中从SyntheticEvent获取FormData的正确方法
React表单用FormData替代手动解构取值的正确做法
你现在靠手动访问event.target[0].value拿表单值,确实可以用FormData来自动收集表单数据,但直接console.log(temp)看不到实际内容——因为FormData是迭代器对象,得用专门的方法读取数据。
正确实现代码
修改你的handleSubmit函数,用FormData.get()获取单个字段,或者遍历所有字段:
export default function Login() { function handleSubmit(event: SyntheticEvent) { event.preventDefault(); const form = event.target as HTMLFormElement; const formData = new FormData(form); // 单个字段取值(示例:获取name为username的输入值) const username = formData.get('username'); console.log('用户名:', username); // 遍历所有表单字段 for (const [key, value] of formData.entries()) { console.log(`${key}: ${value}`); } } return ( <div className="mx-[40%] mt-[10%] "> <form onSubmit={handleSubmit} className="bg-white shadow-md outline-blue-200 outline rounded px-6 pt-6 pb-4 mb-4"> {/* 注意:所有需要收集的输入框必须设置name属性 */} <input type="text" name="username" placeholder="用户名" /> <input type="password" name="password" placeholder="密码" /> <button type="submit">登录</button> </form> </div> ); }
必须注意的点
- 表单里的输入控件一定要加
name属性,FormData就是靠这个属性作为键来存储对应值的,没加name的控件不会被收集。 - TypeScript里必须把
event.target转成HTMLFormElement,不然类型不匹配没法传给FormData构造函数。 - 直接打印FormData对象看不到内容,必须用
get()、getAll()或者entries()这类方法才能读取里面的数据。
内容的提问来源于stack exchange,提问作者CrabBucket
相关产品推荐
相关产品推荐

