简体   繁体   English

在事件处理程序中反应咖喱箭头函数

[英]React curried arrow function in event handlers

How does react know to provide the event as a second argument in the code below? React 如何知道在下面的代码中将事件作为第二个参数提供?

const clickMe = (parameter) => (event) => {
        event.preventDefault();
        // Do something
}
    
<button onClick={clickMe(someParameter)} />

Does it generate this to:它是否会生成以下内容:

<button onClick={(event) => clickMe(someParameter)(event)} />

Or how does it work?或者它是如何工作的? Thanks.谢谢。

Maybe this will help explain it a little better.也许这将有助于更好地解释它。

Closures are functions that carry the information (variables etc.) from their local environment with them when they're returned. 闭包是在返回时携带来自本地环境的信息(变量等)的函数。

I'll work this example without arrow functions as they can be a little deceiving.我将在没有箭头函数的情况下处理此示例,因为它们可能具有欺骗性。

 // `multplyBy` accepts a number as its argument // It returns a new function that "remembers" that number // when it's returned. But that new function *also* // accepts a number function multiplyBy(n) { return function(n2) { return n2 * n; } } // So `multiplyBy(5)` returns a new function // which we assign to the variable `five` const five = multiplyBy(5); // And when we call `five` with a number we get // the result of calling 5 * 10. console.log(five(10));

If you substitute multiplyBy(n) with clickMe(n) you'll see that you'll get a new function that gets used by the click listener, and the first argument of that function will always be the event.如果您用clickMe(n)替换multiplyBy(n) ,您将看到您将获得一个新函数,该函数被单击侦听器使用,并且该函数的第一个参数将始终是事件。

Clickme variable in your code is a function which has return is function e => {...}.代码中的 Clickme 变量是一个返回函数 e => {...} 的函数。 So when you specify like this:所以当你这样指定时:

<button onClick={clickMe(someParameter)} />

it is equivalent to它相当于

<button onClick={e => {...} />

which is basic form of a event handler in react这是反应中事件处理程序的基本形式

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

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