使用reactJS中的变量将值设置为嵌套状态

时间:2018-05-03 07:47:51

标签: reactjs state

我已经定义了一个变量,它会将值粘贴为userInfo中的键。

this.state = {
      userInfo: {
        firstName: "",
        lastName: "",
        email: ""
      }
}
//_________________________________________
onChange = (e)=>{
    var stateChild = e.target.name // stateChild here is variable which will return (firstname, lastName or email) of userInfo
    var userInfo = {
     // ...this.state.userInfo
    }
    userInfo.stateChild = e.target.value; //  I want to paste state child's value here
    console.log(userInfo.stateChild);
}

1 个答案:

答案 0 :(得分:1)

我的处理程序中没有setState。你试过了吗?

this.state = {
  userInfo: {
    firstName: "",
    lastName: "",
    email: ""
  }
};

onChange = e => {
  this.setState(prevState => ({
    userInfo: {
      ...prevState.userInfo,
      [e.target.name]: e.target.value
    }
  }));
};