嵌套更新state中的值
还没有自己写个Demo尝试一遍,先挖个坑
const obj = { a: { // 为了安全的更新 obj.a.c,需要先复制一份 c: 3 }, b: 2 } const obj2 = { // obj 的备份 ...obj, // 覆盖 a a: { // obj.a 的备份 ...obj.a, // 覆盖 c c: 42 } } const arr = ['a', 'b'] // 创建 arr 的备份,并把 c 拼接到最后。 const arr2 = arr.concat('c') // 或者,可以对原来的数组创建复制体 const arr3 = arr.slice() // 修改复制体 arr3.push('c')
e.target.[name]: e.targ
et.value更新
在Javascript中,当创建对象并将该对象的键包装在数组括号[]中时,您可以动态设置该键。
import React, { Component } from "react"; export default class Register extends Component { state = { userName: "", password: "", confirmPassword: "", email: "", }; formSubmit = (e) => { e.preventDefault(); console.log(this.state); }; handleChange = (e)=>{ this.setState({ [e.target.name]: e.target.value }) } render() { const { userName, password, email, confirmPassword } = this.state; return ( <div> <form onSubmit={this.formSubmit}> <div className="form-group"> <label htmlFor="userName">UserName</label> <input type="text" className="form-control" id="userName" name="userName" defaultValue={userName} onChange={this.handleChange} /> </div> <div className="form-group"> <label htmlFor="exampleInputEmail1">Email</label> <input type="email" className="form-control" id="exampleInputEmail1" name="email" defaultValue={email} onChange={this.handleChange} /> </div> <div className="form-group"> <label htmlFor="exampleInputEmail1">Password</label> <input type="password" className="form-control" id="passowrd" name="password" defaultValue={password} onChange={this.handleChange} /> </div> <div className="form-group"> <label htmlFor="exampleInputPassword1">Confirm Password</label> <input type="password" className="form-control" id="confirmPassword" name="confirmPassword" defaultValue={confirmPassword} onChange={this.handleChange} /> </div> <button type="submit" className="btn btn-primary"> Sing up </button> </form> </div> ); } }