React 中setState({key:value}) key值动态变化,如何动态设置key的值

react

 第一种写法:

import React, { Component } from 'react'

class App extends Component {

constructor(props) {

super(props)

this.state = {

username: '',

age: '',

sex:''

}

}

handleChange(field, e) {

this.setState({

[field]: e.target.value

})

setTimeout(() => {

console.log(this.state)

}, 10)

}

render() {

return (

<div>

<input onChange={this.handleChange.bind(this, 'username')}></input>

<input onChange={this.handleChange.bind(this, 'age')}></input>

<input onChange={this.handleChange.bind(this, 'sex')}></input>

</div>

);

}

}

export default App;

第二种写法:

import React, { Component } from 'react'

class App extends Component {

constructor(props) {

super(props)

this.state = {

username: '',

age: '',

sex:''

}

}

handleChange(field, e) {

let data = {}

data[field] = e.target.value

this.setState(data)

setTimeout(() => {

console.log(this.state)

}, 10)

}

render() {

return (

<div>

<input onChange={this.handleChange.bind(this, 'username')}></input>

<input onChange={this.handleChange.bind(this, 'age')}></input>

<input onChange={this.handleChange.bind(this, 'sex')}></input>

</div>

);

}

}

export default App;

以上是 React 中setState({key:value}) key值动态变化,如何动态设置key的值 的全部内容, 来源链接: utcz.com/z/382077.html

回到顶部