【发布时间】:2021-04-30 15:12:50
【问题描述】:
我想接收一些输入字段的值并将它们设置为newValue状态,但是状态的一些属性是对象本身。我希望 newValue 状态的格式为:
{
name : {
firstName : 'Eithan',
lastName :'Auralius'
},
rank : 7
}
现在,对象正在被保存,如下所示:
{
name.firstName : 'Eithan',
name.lastName : 'Auralius',
rank : 7
}
有没有办法通过调整 getValue 函数或输入字段来实现这一点?
//State to store the created or updated user string
const [newValue, setNewValue] = useState();
//onChange triggered function to update
const getValue = (event)=> {
//Setting the value of the state using the changed input fields
setNewValue((newValue)=> {
return {
...newValue,
[event.target.name] : event.target.value,
}
});
}
const submitData = (event)=> {
event.preventDefault();
console.log(newValue);
}
return (
<div className='loginRegister'>
<form onSubmit={submitData}>
<div className='descriptionInput'><div className='description'>First Name</div>
{//the name prop is used to set the field name in the getValue function}
<input type="text" name='name.firstName' defaultValue={member.name.firstName} onChange={getValue}></input></div>
<button>Submit</button>
</form>
</div>
);
【问题讨论】:
-
你好,我认为你的问题是嵌套数组的设置值。
标签: javascript html reactjs