我正在学习React并构建一个CV申请表。
我在将表单中的值存储到数组中的对象时遇到了问题。这很奇怪,因为它似乎对未定义的变量有效,但对已定义的位置变量无效。
我假设我可以让一个对象保持一种状态,换句话说,我不必为每个表单输入都有单独的状态。
import { useState } from 'react';
function EducationInfo() {
const [input, setInput] = useState([]);
const onChange = (e) => {
const { name, value } = e.target;
console.log(`${name}: ${value}`);
};
const addEducation = () => {
const educationNew = {
school: school.value, // 'school' is undefined, red squiggly line in vsCode
degree: degree.value, // 'degree' is undefined, red squiggly line in vsCode
startDate: startDate.value, // 'startDate' is undefined, red squiggly line in vsCode
endDate: endDate.value, // 'endDate' is undefined, red squiggly line in vsCode
location: location.value, // actual variable but undefined when saving to array.
};
setInput([...input, educationNew]);
};
console.log(input);
return (
<>
<form onSubmit={(e) => e.preventDefault}>
<h2>Experience</h2>
<div className='experienceContainer'>
<label htmlFor='school'>School</label>
<input type='text' name='school' id='school' onChange={onChange} />
<label htmlFor='degree'>Degree</label>
<input type='text' name='degree' id='degree' onChange={onChange} />
<div className='dateContainer'>
<label htmlFor='startDate'>Start Date</label>
<input type='date' name='startDate' id='startDate' onChange={onChange} />
<label htmlFor='endDate'>End Date</label>
<input type='date' name='endDate' id='endDate' onChange={onChange} />
</div>
<label htmlFor='location'>Location</label>
<input type='text' name='location' id='location' onChange={onChange} />
</div>
<button
className='SubmitBtn'
type='button'
onClick={addEducation}
onSubmit={(e) => e.preventDefault}
>
Save
</button>
</form>
</>
);
}
export default EducationInfo;
字符串
VS代码:
的数据
这是单击保存按钮后控制台显示的内容:
的
1条答案
按热度按时间7uzetpgm1#
使用一个不同的名称为位置一样locate. value我认为这将工作.
