K
K
KOPC18862016-08-15 18:31:42
JavaScript
KOPC1886, 2016-08-15 18:31:42

How to do it right in React?

Hello!!

class Test extends React.Component
{
  construcrot(props)
  {
    super(props);
    this.handleClick = (value) => this.handleClick.bind(this, value)
  }
  
  handleClick(object) {
    
  }
  
  render() {
    const objectTest = {
      id: 1,
      name: 'Test-1'
    }
  };
  }
    return (
      <div>
        <input type="button" onClick={this.handleClick(objectTest)}>
      </div>
    );
  }
}

How to bind a method correctly if you need to pass an argument to it?
Did I implement correctly?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
E
Eugene, 2016-08-16
@KOPC1886

So:

return (
    <input type="button" onClick={ this.handleClick.bind(this, objectTest) } />
);

Here is an example:
https://jsfiddle.net/t3z1Lz83/1/

M
Mikhail Osher, 2016-08-15
@miraage

This should be enough.
this.handleClick = this.handleClick.bind(this)

T
theWaR_13, 2016-08-15
@theWaR_13

It would be easier to do it like this:

class Test extends React.Component
{ 
  handleClick = object => {
    
  }
  
  render() {
    const objectTest = {
      id: 1,
      name: 'Test-1'
    }
  };
  }
    return (
      <div>
        <input type="button" onClick={this.handleClick(objectTest)}>
      </div>
    );
  }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question