Reactjs 使用表单名称响应表单状态更改
在输入名称中使用数组时,使用react处理输入更改Reactjs 使用表单名称响应表单状态更改,reactjs,forms,input,state,Reactjs,Forms,Input,State,在输入名称中使用数组时,使用react处理输入更改 handleInputChange(event) { const target = event.target; const value = target.type === 'checkbox' ? target.checked : target.value; const name = target.name; this.setState({ [name]: value }); } 如
handleInputChange(event) {
const target = event.target;
const value = target.type === 'checkbox' ? target.checked : target.value;
const name = target.name;
this.setState({
[name]: value
});
}
如果输入名称是,例如,user[email]
,则这不起作用,因为其周围有方括号。有人知道如何使这个字符串或数组通用吗
我的状态如下
this.state =
{
name: '',
type: '',
user: {
email: '',
}
};
nice
this.setState({[name]:value})当您使用嵌套状态时,code>实际上不可行,因为很难将名称映射到实际值
您可以创建一个附加函数,例如handleUserInputChange
,用于设置user
状态对象中的值:
handleUserInputChange(event) {
const { target } = event;
const value = target.type === 'checkbox' ? target.checked : target.value;
const { name } = target;
this.setState(previousState => {
return { user: { ...previousState.user, [name]: value } };
});
}
为什么您需要在输入名称中使用用户[电子邮件]?