简体   繁体   English

反应-为什么onClick中的此功能不起作用?

[英]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? 因此,如果函数具有参数,则应使用“()=> xxx(argument)”;否则,我可以仅使用“ this.xxx”,对吗?

Because doing this.changeName(book) will instantly call the function when rendering. 因为这样做, this.changeName(book)会在渲染时立即调用该函数。 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)是一个箭头函数,它具有与此语法类似(但不是真的)的行为:

() => { 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 : 为了避免这种情况,您可以使用第一个代码示例,或者将函数转换为咖喱函数,然后将第二个语法保留在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. 当在渲染器中调用一次时,此函数将返回另一个接收事件的函数,并首先设置bookInfo

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM