In React, why do I need to bind the onClick function and then call it?

In this tutorial, he uses the onClick function with a link.

<Card onClick={that.deletePerson.bind(null, person)} name={person.name}></Card> 

When I remove a binding like this

 <Card onClick={that.deletePerson(person)} name={person.name}></Card> 

I get an error

Unfixed error: invariant violation: setState (...): cannot be updated during an existing state transition (for example, within render ). render methods should be a pure function of props and condition.

I know what bind does, but why is it needed here? Is onClick not calling a function directly?

(the code is in this JSbin: https://jsbin.com/gutiwu/1/edit )

+8
javascript reactjs bind
source share
1 answer

It uses bind , so the deletePerson method gets the correct argument person .

Since the Card component does not receive the complete person object, this allows it to identify which person the card was clicked on.

In your example, where you removed the onClick={that.deletePerson(person)} binding, it actually evaluates that.deletePerson(person) function and sets it as onClick. The deletePerson method changes the state of the component, as indicated by the error message. (You cannot change state during rendering).

The best solution might be to transfer the identifier to the Card and transfer it back to the application component when you click on delete.

 var Card = React.createClass({ handleClick: function() { this.props.onClick(this.props.id) } render: function () { return ( <div> <h2>{this.props.name}</h2> <img src={this.props.avatar} alt=""/> <div></div> <button onClick={this.handleClick}>Delete Me</button> </div> ) } }) var App = React.createClass({ deletePerson: function (id) { //Delete person using id }, render: function () { var that = this; return ( <div> {this.state.people.map(function (person) { return ( <Card onClick={that.deletePerson} name={person.name} avatar={person.avatar} id={person.id}></Card> ) }, this)} </div> ) } }) 
+7
source share

All Articles