Rufus7
Rufus7

Reputation: 115

React - Why this function in onClick doesn't work?

If I write like this, click button works

<Menu.Item 
    key={book.uid}
    onClick={() => this.changeColor(book)}     
    >

But if I write like this:

onClick={this.changeName(book)}

the click doesn't work.

So if the function has arguments, I should use "() => xxx(argument); otherwise, I can just use "this.xxx", right?

Upvotes: 0

Views: 83

Answers (1)

Treycos
Treycos

Reputation: 7492

Because doing this.changeName(book) will instantly call the function when rendering. And what your function returns is.. not a function, so when you click, nothing will happen.

And () => this.changeColor(book) is an arrow function, it has a similar (but not really) behavior as this syntax :

() => { this.changeColor(book) }

To avoid this, you could use your first code example or transform your function into a curried one and keep the second syntax in the render :

changeName = bookInfo => event => {
    /* Your code here */
}

When called once in the render, this function will return another function receiving the event and set the bookInfo first.

Upvotes: 1

Related Questions