第一种写法:

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;

 

 

相关文章:

  • 2021-10-17
  • 2022-12-23
  • 2021-08-18
  • 2021-07-12
  • 2021-11-27
  • 2022-12-23
  • 2021-11-09
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-02-16
  • 2022-01-25
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案