1
class Product extends Component {
// 1st code
  onAddToCart() {
   console.log('Buy Successfully');
  }
<a className="btn btn-primary" onClick={this.onAddToCard}>Buy Now</a>
// 2nd Code
  onAddToCart(text) {
   console.log(text);
  }
<a className="btn btn-primary" onClick={this.onAddToCard('Buy Successfully')}>Buy Now</a>

The first one run successfully and the second one is failed. As my understand, when react renders of the second one, it will invoke onAddToCart immediately but the first one doesn't do this. So, I don't understand how they work.

HoangBinh
  • 27
  • 2
  • In the second case you are passing the return value of the function as the onClick event handler, while in the first case you are passing the function itself – mousetail Jul 09 '21 at 17:48

1 Answers1

0

Because you are calling your method on the second code. You need to pass to onClick a function, but not return value. Do like this

class Product extends Component {
// 1st code
  onAddToCart() {
   console.log('Buy Successfully');
  }
<a className="btn btn-primary" onClick={this.onAddToCard}>Buy Now</a>
// 2nd Code
  onAddToCart(text) {
   console.log(text);
  }
<a className="btn btn-primary" onClick={()=>{this.onAddToCard('Buy Successfully')}}>Buy Now</a>
Observer
  • 3,506
  • 1
  • 16
  • 32