search
HomeWeb Front-endFront-end Q&Awhat is react currying

In React, currying is a high-level technology about functions. It refers to the function encoding form that receives multiple parameters and finally processes them uniformly by continuing to return functions. Currying The function is not called, but the function is converted. Through currying, the form control data can be easily obtained when processing the form.

what is react currying

The operating environment of this tutorial: Windows 10 system, react17.0.1 version, Dell G3 computer.

What is react currying

Currying of functions:

Continue to return functions through function calls to achieve multiple acceptance of parameters and final unified processing Function encoding form.

Extension:

Higher-order function: If a function meets one of the following two specifications, the function is a higher-order function

1. If the parameter accepted by function a is a function, then a can be called a higher-order function

2. If function a, the return value of the call is still a function, then a can be called a higher-order function

3. Common higher-order functions include: promise, setTimeout, arr.map, etc.

Examples are as follows;

what is react currying

In the form form, use controlled components to bind status data to display form data on click:

import React, {Component} from 'react';
export default class Form extends Component{
  state = {
    userName: '',
    password: ''
  }
  submitForm = (event) => {
    event.preventDefault() //阻止表单提交
    const {userName, password } = this.state;
    alert(`${userName}, ${password}`)
  }
  updateUserName = (event) => {
    this.setState({
      userName: event.target.value,
    })
  }
  updatePassword = (event) => {
    this.setState({
      password: event.target.value,
    })
  }
  render() {
    return (
      <form onSubmit={this.submitForm}>
        用户名:<input type="text" name="userName" onChange={this.updateUserName}/>
        密码: <input type="password" name="password" onChange={this.updatePassword}/>
        <button>登录</button>
      </form>
    )
  }
}

You can see that this method is useful for The situation with many form items is more cumbersome, and you can use function currying to optimize:

import React, {Component} from &#39;react&#39;;
export default class Form extends Component{
  state = {
    userName: &#39;&#39;,
    password: &#39;&#39;
  }
  submitForm = (event) => {
    event.preventDefault() //阻止表单提交
    const {userName, password } = this.state;
    alert(`${userName}, ${password}`)
  }
  updateFormData = (key) => {
    return (event) => {
      this.setState({
        [key]: event.target.value,
      })
    }
  }
  render() {
    return (
      <form onSubmit={this.submitForm}>
        用户名:<input type="text" name="userName" onChange={this.updateFormData(&#39;userName&#39;)}/>
        密码: <input type="password" name="password" onChange={this.updateFormData(&#39;password&#39;)}/>
        <button>登录</button>
      </form>
    )
  }
}

The return value of this.updateFormData() is a callback function, bound to the onChange event, and the parameter is event. In this way, the type can be passed when the first call is made, and the value can be passed when the change event is triggered.

Implementation without using function curry

Bind the onChange event directly as a callback, and you can pass two parameters, type and value, at the same time.

import React, {Component} from &#39;react&#39;;
export default class Form extends Component{
  state = {
    userName: &#39;&#39;,
    password: &#39;&#39;
  }
  submitForm = (event) => {
    event.preventDefault() //阻止表单提交
    const {userName, password } = this.state;
    alert(`${userName}, ${password}`)
  }
  updateFormData = (key, event) => {
    this.setState({
      [key]: event.target.value,
    })
  }
  render() {
    return (
      <form onSubmit={this.submitForm}>
        用户名:<input type="text" name="userName" onChange={(event) => this.updateFormData(&#39;userName&#39;, event)}/>
        密码: <input type="password" name="password" onChange={(event) => this.updateFormData(&#39;password&#39;, event)}/>
        <button>登录</button>
      </form>
    )
  }
}

[Related recommendations: javascript video tutorial, web front-end

The above is the detailed content of what is react currying. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
CSS: Can I use multiple IDs in the same DOM?CSS: Can I use multiple IDs in the same DOM?May 14, 2025 am 12:20 AM

No,youshouldn'tusemultipleIDsinthesameDOM.1)IDsmustbeuniqueperHTMLspecification,andusingduplicatescancauseinconsistentbrowserbehavior.2)Useclassesforstylingmultipleelements,attributeselectorsfortargetingbyattributes,anddescendantselectorsforstructure

The Aims of HTML5: Creating a More Powerful and Accessible WebThe Aims of HTML5: Creating a More Powerful and Accessible WebMay 14, 2025 am 12:18 AM

HTML5aimstoenhancewebcapabilities,makingitmoredynamic,interactive,andaccessible.1)Itsupportsmultimediaelementslikeand,eliminatingtheneedforplugins.2)Semanticelementsimproveaccessibilityandcodereadability.3)Featureslikeenablepowerful,responsivewebappl

Significant Goals of HTML5: Enhancing Web Development and User ExperienceSignificant Goals of HTML5: Enhancing Web Development and User ExperienceMay 14, 2025 am 12:18 AM

HTML5aimstoenhancewebdevelopmentanduserexperiencethroughsemanticstructure,multimediaintegration,andperformanceimprovements.1)Semanticelementslike,,,andimprovereadabilityandaccessibility.2)andtagsallowseamlessmultimediaembeddingwithoutplugins.3)Featur

HTML5: Is it secure?HTML5: Is it secure?May 14, 2025 am 12:15 AM

HTML5isnotinherentlyinsecure,butitsfeaturescanleadtosecurityrisksifmisusedorimproperlyimplemented.1)Usethesandboxattributeiniframestocontrolembeddedcontentandpreventvulnerabilitieslikeclickjacking.2)AvoidstoringsensitivedatainWebStorageduetoitsaccess

HTML5 goals in comparison with older HTML versionsHTML5 goals in comparison with older HTML versionsMay 14, 2025 am 12:14 AM

HTML5aimedtoenhancewebdevelopmentbyintroducingsemanticelements,nativemultimediasupport,improvedformelements,andofflinecapabilities,contrastingwiththelimitationsofHTML4andXHTML.1)Itintroducedsemantictagslike,,,improvingstructureandSEO.2)Nativeaudioand

CSS: Is it bad to use ID selector?CSS: Is it bad to use ID selector?May 13, 2025 am 12:14 AM

Using ID selectors is not inherently bad in CSS, but should be used with caution. 1) ID selector is suitable for unique elements or JavaScript hooks. 2) For general styles, class selectors should be used as they are more flexible and maintainable. By balancing the use of ID and class, a more robust and efficient CSS architecture can be implemented.

HTML5: Goals in 2024HTML5: Goals in 2024May 13, 2025 am 12:13 AM

HTML5'sgoalsin2024focusonrefinementandoptimization,notnewfeatures.1)Enhanceperformanceandefficiencythroughoptimizedrendering.2)Improveaccessibilitywithrefinedattributesandelements.3)Addresssecurityconcerns,particularlyXSS,withwiderCSPadoption.4)Ensur

What are the main areas where HTML5 tried to improve?What are the main areas where HTML5 tried to improve?May 13, 2025 am 12:12 AM

HTML5aimedtoimprovewebdevelopmentinfourkeyareas:1)Multimediasupport,2)Semanticstructure,3)Formcapabilities,and4)Offlineandstorageoptions.1)HTML5introducedandelements,simplifyingmediaembeddingandenhancinguserexperience.2)Newsemanticelementslikeandimpr

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software