P
P
Pogran2016-08-31 10:04:02
JavaScript
Pogran, 2016-08-31 10:04:02

How to pass parameters to a method?

I have this code

constructor(props) {
    super(props);

    this.updateClick = this.updateClick.bind(this);
  }

  updateClick(e) {
    e.preventDefault();
  }

  renderTreeString(key, value) {
    return (
      <div style={{margin: '3px 0'}} key={key} >
        <div className="pull-left" style={{width: '200px'}}><b>{key}</b>: {value}</div>
        <button onClick={this.updateClick('params')} style={{marginLeft: '6px'}} type="button" className="btn btn-primary btn-xs">Update</button>
      </div>
    );
  }

In the renderTreeString method, I have an onClick event in which I call the updateClick method and want to pass a parameter to it. How to do it correctly, given that in the same method I then listen to the event (e) ?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim, 2016-08-31
@Pogran

Good afternoon, in order for your progress to be faster and more useful, you need to improve your knowledge of native js.
First - onClick={this.updateClick('params')}- what do you expect from such a record? Let's think about it: in onClick you must pass a handler function, and you pass the RESULT to this.updateClick function because you call it with ( )
Secondly, as you were rightly told, you can use .bind to pass parameters.
To do this, first go to MDN , read. We are trying to pass a function with a parameter as homework. Hint: .bind puts your options at the beginning. That is, all arguments are shifted (including "e").
PS If it does not work out, you can see the answer at the link .
PPS It is very important to understand what isthe result of the function. That is, in your question, you passed e.preventDefault() to onClick, and this is exactly what, and not "a function that would work on click and e.preventDefault() would occur). In the case of bind, you pass the result the work of the bind function, which is a function, in other words - "everything is correct, a function is passed to onClick".

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question