SoFunction
Updated on 2025-03-02

Implementation of Event Processing and Curryization in React

1. Event handling

Elements in React can also accept and handle events, but there is a little syntax difference.

In React, all events are named in small camels, not pure lowercase of native DOM. All events require us to pass in a function, not a string.

For example:

const Button = () => {
    const handleClick = () => {
        ('click')
    }
    return <button onClick={handleClick}>click button</button>
}

When the callback function of the event is relatively simple, we can also abbreviate the arrow anonymous function, for example:

const Button = () => {
    return (
        <button
            onClick={() => ('click')}
        >
            click button
        </button>)
}

Block default behavior

Cannot return in Reactfalseto prevent default behavior, such as form submission, a tag jump. We have to call it explicitlypreventDefaultfunction to prevent these default behaviors.

const Link = () => {
    return <a
        href="" rel="external nofollow"  rel="external nofollow" 
        onClick={(e) => ()}
    >
        link
    </a>
}

Synthesis Events

Almost all event handlers in React are one(event)=>voidFunctions. If we use typescript, we can clearly see the function type corresponding to each event. React itself also declares many event and event handling function types, such as mouse events:MouseEvent<T = Element>andMouseEventHandler<T = Element>, when we use it, we can define function types or parameter types according to our preferences, like this:

const Link = () => {
    const handleClick = (e: MouseEvent) => {
        ()
        ('click')
    }
    const handleMouseEnter:MouseEventHandler = (e) => {
        ('mouse enter')
    }
    return <a
        href="" rel="external nofollow"  rel="external nofollow" 
        onMouseEnter={handleMouseEnter}
        onClick={handleClick}
    >
        link
    </a>
}

In React, all events are synthetic events defined by React according to the W3C specification, so we don't have to worry about compatibility at all. React events are not exactly the same as native events.

Click here to view the synthesis event document

2. Curry

The name Currying may be a bit unfamiliar with Android development because we generally use Java development, because early Java did not support functional programming (FP), and Currying is a functional programming idea.

In short, it is to turn aMulti-parameter functionbecomeSingle parameter function, give a chestnut:

// Curryized single parameter functionfunction sumCurrying(a) {
  return (b) =&gt; {
    return (c) =&gt; {
      return a + b + c;
    };
  };
}
//Ordinary multi-parameter functionfunction sumNormal(a, b, c) {
  return a + b + c
}
(sumCurrying(1)(2)(3));
(sumNormal(1, 2, 3));

The essence of Currying is a feature of higher-order functions: the return value of a function can be a function.

The above example seems to be a little bit off your pants and fart, which seems meaningless. But in actual engineering, Curry is a very practical trick. Most commonly used in event processing scenarios where incoming values ​​are required.

As we said above, the event callback functions in React have fixed function types, almost all(event)=>voidfunction. We need to pass in some parameters to this event handler?

const List = () => {
    const list = [
        { id: 1, name: 'tom' },
        { id: 2, name: 'jerry' },
        { id: 3, name: 'jack' },
        { id: 4, name: 'lily' },
    ]
    const handleClick = (id: number) => {
        (id)
    }
    return <ul>
        {(item => <li
                onClick={() => handleClick()}
                key={}
            >
                {}
            </li>
        )}
    </ul>
}

This seems inelegant. We have declared the handle function, but we have to write the arrow function in the line in the event handler function. How can we handle it more elegantly?

It's actually very simple. We just need to insert an arrow into the original handle function, just like this:

//before
const handleClick = (id: number) => {
  (id)
}
//after
const handleClick = (id: number) => (e:MouseEvent) => {
  (id)
}

Then our onClick event callback function can be changed toonClick={handleClick()}, does this look more elegant?

In fact, this design idea can be said to be thorough at once, but I will tell you now that this idea is called:Curry

The purpose of currying

You might ask me that Currying looks just to make our code a little more elegant, and it seems that there is nothing fundamentally changing at the moment.

But in fact, Curry helps us realize that more functions are needed. We use a log output function as an example:

//Original functionconst log = (date, importance, message) =&gt; {
  alert(`[${()}:${()}] [${importance}] ${message}`);
}
//Currieconst logCurry = (date) =&gt; (importance) =&gt; (message) =&gt; { 
  alert(`[${()}:${()}] [${importance}] ${message}`);
}

After currying, the function becomes called like this:logCurry(new Date())("DEBUG")("some debug");

Now we have these functions:

// logNow will be a function with a log with the first parameter fixedlet logNow = logCurry(new Date());

// Use itlogNow("INFO", "message"); // [HH:mm] INFO message

// debugNow will be a function with fixed first and second parameterslet debugNow = logNow("DEBUG");

debugNow("message"); // [HH:mm] DEBUG message

It seems that only a few arrows have been added, but in fact the flexibility of our function has increased greatly. By fixing different parameters, we obtain multiple functions from a function declaration.

A simple example

const Form = () =&gt; {
   const [form, setForm] = ({});
   const update = (name) =&gt; (event) =&gt; {
     setForm({
       ...form,
       [name]: ,
     });
   }
   const handleSubmit = (event) =&gt; {
     ();
     alert(`${(form)}`);
   }
   return (
     &lt;div&gt;
       &lt;h1&gt;Currying form&lt;/h1&gt;
       &lt;FormItem label="username" name='username' update={update} /&gt;
       &lt;FormItem label="Nick name" name='nickname' update={update} /&gt;
       &lt;FormItem label="Mail" name='email' update={update} /&gt;
       &lt;button onClick={handleSubmit}&gt;submit&lt;/button&gt;
     &lt;/div&gt;
   )
 }

 const FormItem = ({ label, name, update }) =&gt; {
   return (
     &lt;div style={{ 'display': 'flex' }}&gt;
       &lt;label&gt;{label}&lt;/label&gt;
       &lt;input onChange={update(name)} type="text" placeholder={`Please enter${label}`} /&gt;
     &lt;/div&gt;
   );
 };

This is the end of this article about the implementation of event processing and curryization in react. For more related react event processing and curryization content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!