【问题标题】:React form state changes using form name使用表单名称响应表单状态更改
【发布时间】:2018-12-25 08:14:44
【问题描述】:

在输入名称中使用数组时使用 react 处理输入更改;

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: '',
   }

};

【问题讨论】:

  • 为什么需要在输入名称中使用user[email]?

标签: reactjs forms input state


【解决方案1】:

当你有嵌套状态时,漂亮的this.setState({ [name]: value }); 是不可行的,因为很难将名称映射到实际值。

您可以创建一个附加功能,例如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 } };
    });
}

【讨论】:

    猜你喜欢
    • 2021-04-12
    • 1970-01-01
    • 2020-09-23
    • 2018-02-01
    • 1970-01-01
    • 2020-07-10
    • 1970-01-01
    • 2019-09-07
    • 1970-01-01
    相关资源
    最近更新 更多