第一种写法:
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;