我正在尝试从这样的表单输入数据 -
<h1>Company Position</h1>
<input
name="company.position"
type="text"
onChange={(e) => functions.setData(e)}
value={data.company.position}
/>
进入这样的状态对象 -
const [ form, setValues ] = useState({
name : 'Jo Smith',
email : '[email protected] /cdn-cgi/l/email-protection',
phone : null,
company : {
name : null,
position : null
}
});
使用我传入目标的handleStateChange函数
const handleStateChange = (e) => {
e.preventDefault();
setValues({
...form,
[e.target.name]: e.target.value
});
};
我似乎无法更新状态内的公司对象,我假设它会将 company.name 识别为目标名称。
任何帮助,将不胜感激。
e.target.name
is company.position
,你不能像这样设置嵌套属性obj["company.position"]
,你必须将其拆分:
<input
name="company.position"
type="text"
onChange={e => functions.setData(e)}
value={data.company.position}
/>;
const handleStateChange = e => {
e.preventDefault();
const [section, key] = e.target.name.split(".");
// section is : company
// key is : position
if (key) {
// if you have nested keys to update
setValues({
...form,
[section]: {
...form[section],
[key]: e.target.value
}
});
} else {
// if you're updating on the first level
setValues({
...form,
[section]: e.target.value
});
}
};
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)