0

I have multiple inputs; how can I know which input is changed? I think one way to do it is I can pass additional param to my handleChange function. I know I can do this in jsx onChange={this.handleChange.bind(this, 'name'); But I don't know how to do that since the constructor had bind the function.

class HelloWorldComponent extends React.Component {

  constructor(){
    super();

    this.handleChange = this.handleChange.bind(this);

    this.state = {
      name:"",
      age:""
    }
  }

  render() {
    const person = {"name":"james", "age":18};
    return (   
      <div>
      <input onChange={this.handleChange} type="text" placeholder="name" defaultValue={person.name} /><br />
      <input onChange={this.handleChange} type="text" placeholder="age" defaultValue={person.age} />
      </div>
    );
  }

  handleChange(e){
    // how to get name and age here?
    console.log(e.target.value)
  }
}

http://jsbin.com/cubofurihu/edit?js,console,output

Chris Martin
  • 30,334
  • 10
  • 78
  • 137
Alex Yong
  • 7,425
  • 8
  • 24
  • 41
  • Possible duplicate of [React js onClick can't pass value to method](http://stackoverflow.com/questions/29810914/react-js-onclick-cant-pass-value-to-method) – Abdennour TOUMI Mar 07 '17 at 04:18

1 Answers1

0

bind does not do any call for the function , it just assignes the scope this to the function .

Then , Don't write onChange={this.handleChange.bind(this, 'name')}

But , write as following:

onChange={(e) => this.handleChange(e, 'name')}

assuming handleChange is :

   handleChange(e, param) {
      console.log(e.target.value); 
      console.log(param) // 'name'
   } 
Abdennour TOUMI
  • 87,526
  • 38
  • 249
  • 254