亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Table of Contents
ES6 Syntax Cheat Sheet
Arrow function
Function without parameters
Function with a single parameter
Function with multiple parameters
Currying in Functional Programming
Propagation syntax
Extended syntax in function calls
Extended syntax in array literals
Extended syntax in object literals
Expand operator in React
Higher-order functions
高階組件
摘要
Home CMS Tutorial WordPress A friendly introduction to high-level components in React

A friendly introduction to high-level components in React

Sep 04, 2023 pm 02:01 PM

Higher-Order Components (HOC) are an interesting technique in React for refactoring similar components that share almost the same logic. I know this sounds abstract and advanced. However, it is an architectural pattern that is not specific to React, so you can do a lot with this approach.

For example, you can use it to add a loading indicator to a component without adjusting the original component, or you can hide a component's properties to make it less verbose. There are many applications and I tried to cover most of them in this tutorial.

There are several other tutorials that can teach you about HOCs, but most of them are aimed at advanced React developers. When I started learning React, I struggled to understand the concept of higher order components and how to incorporate HOCs into my projects to write better code. This article explains everything you need to know about HOCs from inception to incubation.

Overview

This tutorial is divided into three parts. The first part will introduce the concept of higher-order components. Here we will discuss the syntax you need to know before looking at higher order functions and HOCs. Part Two is the most exciting part of the series, where you'll see practical examples of HOCs. We will use HOC to create forms, authorizations and many other things.

In the third part of this tutorial, we will focus more on best practices and things to consider when implementing higher-order components. We'll also briefly cover alternative patterns for code sharing in React, such as Render props.

Before starting, it’s best to take a look at the tutorials on stateful components and stateless components to better understand React’s component architecture.

ES6 Syntax Cheat Sheet

We'll get started soon. But before that, there are a few things I think you should know. I prefer to use ES6 syntax whenever possible, it works well with HOCs. As a beginner, HOC makes sense, but some of the ES6 syntax doesn't. Therefore, I recommend that you skim this section first so that you can come back to it later.

Arrow function

Arrow functions are regular function expressions, but with shorter syntax. They are best suited for non-method functions, which is what we are particularly interested in. Here are some examples to get you started:

Function without parameters

/* Functions without parameters */
function () {
    return "This is a function expression";
}

// is equivalent to

() => {
 return "This is an arrow function expression"
}

// or 

() => "Arrow with a shorter syntax"

Function with a single parameter

/* Function with a single parameter */

function (param) {
  return { title: "This function accepts a parameter and returns an object",
          params: param}
}

// is syntax-equivalent to 

param => {
    return { title: "This arrow function accepts a single parameter",
        params: param }
}

Function with multiple parameters

/* Function with multiple parameters */

function (param1, param2) {
  return { title: "This function accepts multiple parameters",
          params: [param1,param2]}
}

// is syntax-equivalent to 

(param1, param2) => {
    return {title: "Arrow function with multiple parameters",
    params: [param1, param2]
    }
}

// or

(param1, param2) => ({
      title: "Arrow function with multiple parameters",
    params: [param1, param2]
    })

Currying in Functional Programming

While the name implies that it is related to an exotic dish in popular Indian cuisine, this is not the case. Currying helps you decompose a function that accepts multiple arguments into a series of functions that accept one argument at a time. Here is an example:

//Usual sum function
const sum = (a, b) => a + b

//Curried sum function 
const curriedSum = function (a) {
    return function (b) {
        return a+b
    }

//Curried sum function using arrow syntax
const curriedSum = a => b => a+b

curriedSum(5)(4)
//9

The function accepts only one parameter and returns a function that accepts another parameter, and this continues until all parameters are satisfied.

curriedSum
// (a) => (b) => a+b

curriedSum(4)

// (b) => 4+b

curriedSum(4)(5)

//4+5

A closely related term is called "partial application". Some applications create new functions by pre-populating some parameters of an existing function. The arity of the newly created function (i.e. the number of arguments) will be less than the arity of the original function.

Propagation syntax

The expansion operator expands the contents of an array, string, or object expression. The following is a list of operations you can perform using the spread operator

Extended syntax in function calls

/*Spread Syntax in Function Calls */
const add = (x,y,z) => x+y+z

const args = [1,2,3]

add(...args) 
// 6

Extended syntax in array literals

/* Spread in Array Literals */

const twoAndThree = ['two', 'three']; 
const numbers = ['one', ...twoAndThree, 'four', 'five']; 
// ["one", "two", "three", "four", "five"]

Extended syntax in object literals

/* Spread in Object Literals */

const contactName = {
  name: {
    first: "Foo",
    middle: "Lux",
    last: "Bar"
  }
}
const contactData = {
  email: "fooluxbar@example.com",
  phone: "1234567890"
}

const contact = {...contactName, ...contactData}
/* { 
    name: {
        first: "Foo",
        middle: "Lux",
        last: "Bar"
    }
    email: "fooluxbar@example.com"
    phone: "1234567890"
  }
  
*/
        

I personally like the way three dots make it easier for you to pass existing props to child components or create new ones.

Expand operator in React

const ParentComponent = (props) => {
  const newProps = { foo: 'default' };
  
  return (
      <ChildComponent 
  		{...props} {...newProps} 
  	/>
  )
}

Now that we understand the basic ES6 syntax for building HOCs, let’s see what they are.

Higher-order functions

What is a higher-order function? Wikipedia has a simple definition:

In mathematics and computer science, a higher-order function (also called a functional, functional form, or functor) is a function that accepts one or more functions as arguments or returns a function as its result, or both. function of it.

You've probably used higher-order functions in JavaScript in some form before, because that's how JavaScript works. Functions that pass anonymous functions or callbacks as arguments or return another function - all of these are higher-order functions. The code below creates an essentially higher order calculator function.

const calculator = (inputFunction) => 
    	(...args) => {
        
       const resultValue = inputFunction(...args);
       console.log(resultValue);
          
       return resultValue;
        }

const add = (...all) => {
	return all.reduce( (a,b) => a+b,0)	;
  
	}
  
 
const multiply = (...all) => {
  return all.reduce((a,b)=> a*b,1);
 
  }

Let’s take a deeper look at this. calculator() Accepts a function as input and returns another function - this is exactly our definition of a higher-order function. Because we used rest parameters syntax, the returned function collects all of its parameters in an array.

Then, the input function is called with all arguments passed and the output is logged to the console. So calculator is a curried higher-order function, and you can use calculator like this:

calculator(multiply)(2,4);
// returns 8

calculator(add)(3,6,9,12,15,18); 
// returns 63

插入一個(gè)函數(shù),例如 add()multiply() 和任意數(shù)量的參數(shù),以及 calculator()將從那里拿走它。所以計(jì)算器是一個(gè)擴(kuò)展了 add()multiply() 功能的容器。它使我們能夠在更高或更抽象的層面上處理問題。乍一看,這種方法的好處包括:

  1. 代碼可以在多個(gè)函數(shù)中重復(fù)使用。
  2. 您可以在容器級(jí)別添加所有算術(shù)運(yùn)算通用的額外功能。
  3. 更具可讀性,并且能更好地表達(dá)程序員的意圖。

現(xiàn)在我們對(duì)高階函數(shù)有了一個(gè)很好的了解,讓我們看看高階組件的能力。

高階組件

高階組件是一個(gè)接受組件作為參數(shù)并返回該組件的擴(kuò)展版本的函數(shù)。

(InputComponent) => {
    return ExtendedComponent 
    }
    
// or alternatively

InputComponent => ExtendedComponent

擴(kuò)展組件 組成 InputComponentExtendedComponent 就像一個(gè)容器。它呈現(xiàn) InputComponent,但因?yàn)槲覀兎祷匾粋€(gè)新組件,所以它添加了一個(gè)額外的抽象層。您可以使用此層添加狀態(tài)、行為甚至樣式。如果您愿意,您甚至可以決定根本不渲染 InputComponent — HOC 能夠做到這一點(diǎn)以及更多。

下面的圖片應(yīng)該可以消除混亂(如果有的話)。

React 中高階組件的友好介紹

理論已經(jīng)講完了,讓我們開始看代碼。下面是一個(gè)非常簡單的 HOC 示例,它將輸入組件包裝在 <div> 標(biāo)記周圍。從這里開始,我將把 InputComponent 稱為 WrappedComponent,因?yàn)檫@是慣例。不過,您可以隨意命名它。

/* The `with` prefix for the function name is a naming convention.
You can name your function anything you want as long as it's meaningful 
*/

const withGreyBg = WrappedComponent => class NewComponent extends Component {
  
  const bgStyle = {
  		backgroundColor: 'grey',
	};
    
  render() {
    return (
      <div className="wrapper" style={bgStyle}>

        <WrappedComponent {...this.props} />
      </div>
    );
  }
};

const SmallCardWithGreyBg = withGreyBg(SmallCard);
const BigCardWithGreyBg = withGreyBg(BigCard);
const HugeCardWithGreyBg = withGreyBg(HugeCard);

class CardsDemo extends Component {
    render() {
        <SmallCardWithGreyBg {...this.props} />
        <BigCardWithGreyBg {...this.props} />
        <HugeCardWithGreyBg {...this.props />
    }
}

withGreyBg 函數(shù)將一個(gè)組件作為輸入并返回一個(gè)新組件。我們不是直接組合 Card 組件并將樣式標(biāo)簽附加到每個(gè)單獨(dú)的組件,而是創(chuàng)建一個(gè) HOC 來實(shí)現(xiàn)此目的。高階組件包裝原始組件并在其周圍添加 <div> 標(biāo)簽。需要注意的是,這里你必須手動(dòng)將 props 分兩層傳遞下去。我們沒有做任何花哨的事情,但這就是正常的 HOC 的樣子。下圖更詳細(xì)地演示了 withGreyBg() 示例。

React 中高階組件的友好介紹

雖然這目前看起來不是特別有用,但好處并不小。考慮這種情況。您正在使用 React 路由器,并且需要保護(hù)某些路由 - 如果用戶未經(jīng)過身份驗(yàn)證,則對(duì)這些路由的所有請(qǐng)求都應(yīng)重定向到 /login。我們可以使用 HOC 來有效管理受保護(hù)的路由,而不是重復(fù)身份驗(yàn)證代碼。好奇想知道怎么做嗎?我們將在下一個(gè)教程中介紹這一點(diǎn)以及更多內(nèi)容。

注意:ECMAScript 中提出了一個(gè)稱為裝飾器的功能,可以輕松使用 HOC。但是,它仍然是一個(gè)實(shí)驗(yàn)性功能,因此我決定不在本教程中使用它。如果您使用的是 create-react-app,則需要先彈出才能使用裝飾器。如果您運(yùn)行的是最新版本的 Babel (Babel 7),您所需要做的就是安裝 <em>babel-preset-stage-0</em> 然后將其添加到 webpack.config.dev.js 的插件列表中,如下所示。

// Process JS with Babel.
        {
            test: /\.(js|jsx|mjs)$/,
            include: paths.appSrc,
            loader: require.resolve('babel-loader'),
            options: {
              
              // This is a feature of `babel-loader` for webpack (not Babel itself).
              // It enables caching results in ./node_modules/.cache/babel-loader/
              // directory for faster rebuilds.
              cacheDirectory: true,
              presets: ['stage-0']
        },

摘要

在本教程中,我們學(xué)習(xí)了 HOC 的基本概念。 HOC 是構(gòu)建可重用組件的流行技術(shù)。我們首先討論基本的 ES6 語法,以便您更容易習(xí)慣箭頭函數(shù)并編寫現(xiàn)代 JavaScript 代碼。

然后我們了解了高階函數(shù)及其工作原理。最后,我們接觸了高階組件并從頭開始創(chuàng)建了 HOC。

接下來,我們將通過實(shí)際示例介紹不同的 HOC 技術(shù)。在那之前請(qǐng)繼續(xù)關(guān)注。在評(píng)論部分分享你的想法。

The above is the detailed content of A friendly introduction to high-level components in React. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

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.

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 Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1488
72
How to diagnose high CPU usage caused by WordPress How to diagnose high CPU usage caused by WordPress Jul 06, 2025 am 12:08 AM

The main reasons why WordPress causes the surge in server CPU usage include plug-in problems, inefficient database query, poor quality of theme code, or surge in traffic. 1. First, confirm whether it is a high load caused by WordPress through top, htop or control panel tools; 2. Enter troubleshooting mode to gradually enable plug-ins to troubleshoot performance bottlenecks, use QueryMonitor to analyze the plug-in execution and delete or replace inefficient plug-ins; 3. Install cache plug-ins, clean up redundant data, analyze slow query logs to optimize the database; 4. Check whether the topic has problems such as overloading content, complex queries, or lack of caching mechanisms. It is recommended to use standard topic tests to compare and optimize the code logic. Follow the above steps to check and solve the location and solve the problem one by one.

How to minify JavaScript files in WordPress How to minify JavaScript files in WordPress Jul 07, 2025 am 01:11 AM

Miniving JavaScript files can improve WordPress website loading speed by removing blanks, comments, and useless code. 1. Use cache plug-ins that support merge compression, such as W3TotalCache, enable and select compression mode in the "Minify" option; 2. Use a dedicated compression plug-in such as FastVelocityMinify to provide more granular control; 3. Manually compress JS files and upload them through FTP, suitable for users familiar with development tools. Note that some themes or plug-in scripts may conflict with the compression function, and you need to thoroughly test the website functions after activation.

How to optimize WordPress without plugins How to optimize WordPress without plugins Jul 05, 2025 am 12:01 AM

Methods to optimize WordPress sites that do not rely on plug-ins include: 1. Use lightweight themes, such as Astra or GeneratePress, to avoid pile-up themes; 2. Manually compress and merge CSS and JS files to reduce HTTP requests; 3. Optimize images before uploading, use WebP format and control file size; 4. Configure.htaccess to enable browser cache, and connect to CDN to improve static resource loading speed; 5. Limit article revisions and regularly clean database redundant data.

How to prevent comment spam programmatically How to prevent comment spam programmatically Jul 08, 2025 am 12:04 AM

The most effective way to prevent comment spam is to automatically identify and intercept it through programmatic means. 1. Use verification code mechanisms (such as Googler CAPTCHA or hCaptcha) to effectively distinguish between humans and robots, especially suitable for public websites; 2. Set hidden fields (Honeypot technology), and use robots to automatically fill in features to identify spam comments without affecting user experience; 3. Check the blacklist of comment content keywords, filter spam information through sensitive word matching, and pay attention to avoid misjudgment; 4. Judge the frequency and source IP of comments, limit the number of submissions per unit time and establish a blacklist; 5. Use third-party anti-spam services (such as Akismet, Cloudflare) to improve identification accuracy. Can be based on the website

How to use the Transients API for caching How to use the Transients API for caching Jul 05, 2025 am 12:05 AM

TransientsAPI is a built-in tool in WordPress for temporarily storing automatic expiration data. Its core functions are set_transient, get_transient and delete_transient. Compared with OptionsAPI, transients supports setting time of survival (TTL), which is suitable for scenarios such as cache API request results and complex computing data. When using it, you need to pay attention to the uniqueness of key naming and namespace, cache "lazy deletion" mechanism, and the issue that may not last in the object cache environment. Typical application scenarios include reducing external request frequency, controlling code execution rhythm, and improving page loading performance.

How to enqueue assets for a Gutenberg block How to enqueue assets for a Gutenberg block Jul 09, 2025 am 12:14 AM

When developing Gutenberg blocks, the correct method of enqueue assets includes: 1. Use register_block_type to specify the paths of editor_script, editor_style and style; 2. Register resources through wp_register_script and wp_register_style in functions.php or plug-in, and set the correct dependencies and versions; 3. Configure the build tool to output the appropriate module format and ensure that the path is consistent; 4. Control the loading logic of the front-end style through add_theme_support or enqueue_block_assets to ensure that the loading logic of the front-end style is ensured.

How to add custom fields to users How to add custom fields to users Jul 06, 2025 am 12:18 AM

To add custom user fields, you need to select the extension method according to the platform and pay attention to data verification and permission control. Common practices include: 1. Use additional tables or key-value pairs of the database to store information; 2. Add input boxes to the front end and integrate with the back end; 3. Constrain format checks and access permissions for sensitive data; 4. Update interfaces and templates to support new field display and editing, while taking into account mobile adaptation and user experience.

How to add custom rewrite rules How to add custom rewrite rules Jul 08, 2025 am 12:11 AM

The key to adding custom rewrite rules in WordPress is to use the add_rewrite_rule function and make sure the rules take effect correctly. 1. Use add_rewrite_rule to register the rule, the format is add_rewrite_rule($regex,$redirect,$after), where $regex is a regular expression matching URL, $redirect specifies the actual query, and $after controls the rule location; 2. Custom query variables need to be added through add_filter; 3. After modification, the fixed link settings must be refreshed; 4. It is recommended to place the rule in 'top' to avoid conflicts; 5. You can use the plug-in to view the current rule for convenience

See all articles