When setState({key:value}) in React, when the passed key is a variable, the value of state is dynamically obtained and set

Take a registered component as an example

class Register extends Component {
  constructor(props){
    super(props)
    this.state = {
      username:'',
      password:'',
      password2:'',
      type:'求职者'
    }
  }

If you want to modify the values ​​of the four state attributes through the same handleChange method, you need to dynamically pass in the attribute parameters, write a wrong place first, and see what happens

handleChange(name,val){
    this.setState({
      name:val
    })
  }

In fact, if the name in the code in vscode is not highlighted, that is to say, Ming is not used at all, this is also a reminder

transfer

<InputItem onChange={(val)=>{this.handleChange('username',val)}} placeholder="请输入用户名">用户名:</InputItem>
<InputItem onChange={(val)=>{this.handleChange('password',val)}} type='password' placeholder="请输入密码">密码:</InputItem>

As a result, the reminder is as follows, and the ajax request is not sent

Change the handleChange method by adding square brackets to the name

handleChange(name,val){
    this.setState({
    [name]:val
    })
  }

Name is highlighted in vscode

Request sent smoothly

 

Guess you like

Origin blog.csdn.net/a1059526327/article/details/106959180