我找不到这个反应代码有什么问题,但是当尝试 console.log 该项目时,除了注释字段之外的所有字段都未定义。我决定使用基于类的组件,希望是函数组件导致了错误,但类组件声明 typeError firstName 为 null。这是功能组件和错误消息Objectaddress: undefinedbirthday: undefinedcompany: undefinedemail: undefinedfirstName: undefinedlastName: undefinednote: "d"phone: undefinedsocialProfile: undefinedurl: undefined__proto__: Objectimport React, {useState} from 'react'function Phonebookform() { const [phonebook, setPhonebook] = useState({ firstName:'', lastName:'', company:'', phone:'', email:'', note:'', url:'', address:'', birthday:'', socialProfile:'' }) const handleChange = (e) =>{ setPhonebook({ [e.target.name]:e.target.value }) } const handleSubmit = (e) =>{ e.preventDefault() const item = { firstName: phonebook.firstName, lastName: phonebook.lastName, company: phonebook.company, phone: phonebook.phone, email: phonebook.email, url: phonebook.url, note: phonebook.note, address: phonebook.address, birthday: phonebook.birthday, socialProfile: phonebook.socialProfile } console.log(item) } return ( <form id='form' onSubmit={handleSubmit} > <input name='firstName' value={phonebook.firstName} onChange={handleChange} type="text" placeholder="First Name" /> <input name='lastName' value={phonebook.lastName} onChange={handleChange} type="text" placeholder="Last Name" /> <input name='company' value={phonebook.company} onChange={handleChange} type="text" placeholder="Company" /> <input name='phone' value={phonebook.phone} onChange={handleChange} type="text" placeholder="Phone" />
2 回答
手掌心
TA贡献1942条经验 获得超3个赞
我会坚持使用功能组件。问题是您正在将电话簿对象更改为仅包含一个属性。
我想你想要这样的东西:
const handleChange = (e) => { setPhonebook((prevPhonebook) => ({ ...prevPhonebook, [e.target.name]: e.target.value })); };
我不确定您以前是否见过扩展运算符,但这将允许您维护以前的值并更新更改的值。
添加回答
举报
0/150
提交
取消