search
HomeWeb Front-endJS TutorialDetailed introduction to React component pattern (with examples)

Detailed introduction to React component pattern (with examples)

Feb 21, 2019 pm 05:45 PM
javascriptreact.jsfront endprogrammer

This article brings you a detailed introduction to the React component pattern (with examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Components are the heart of React, so knowing how to leverage them is crucial to creating great design structures.

What are components

According to the React official website, “Components allow you to split your UI into independent, reusable parts and manage each part independently. .”

When you install npm install react for the first time, you’ll get one thing: components and their APIs. Similar to JavaScript functions, components accept inputs called "props" and return React elements that describe (declare) the appearance of the user interface (UI). This is why React is called a declarative API because you tell it what you want the UI to look like and React takes care of the rest.

You can think of the declarative style as when you take a taxi to a destination

, you only need to tell the driver where to go, and he will drive you there. Imperative programming is the opposite—you have to drive there yourself.

API of components

After installing React, you can use the API provided by React, which can basically be divided into 5 types.

Detailed introduction to React component pattern (with examples)

  • render

  • state

  • props

  • context

  • ##lifecycle events

  • ##Although a component can use all of the above
API

, but a component usually uses only a few APIs, while other components only use other APIs. You can use different APIs to divide components into two types:

stateful

and stateless.

    Stateful components usually use
  • API

    : render, state and life cycle related events.

  • Stateless components usually use
  • API

    : render, props and context.

Detailed introduction to React component pattern (with examples)The above is why we want to introduce the

Component pattern

. The component pattern is a best practice when using React. The component pattern was originally introduced to separate the data logic and UI presentation layer. By dividing responsibilities between components, you create more reusable, cohesive components that can be used to compose complex UIs, which is especially important when building scalable applications.

Component pattern

Usually there are the following component patterns:

    Container (container component)
  • Presentational (display components)
  • Higher order components (advanced components)
  • Render callback (rendering callback)
Container (container component)

"The container component just takes the data and then renders the child components" —— Jason Bonta

Detailed introduction to React component pattern (with examples)Container component is your data or logic layer and leverages the stateful API. Using lifecycle events, you can connect state to

redux or Flux's storage and pass data and callbacks as props are passed to child components.


In the render method of the container component, you can use the display component to render specific styles. In order to have access to all state APIs, container components must be declared as classes instead of using functional methods.

In the example below, we have a class component named Greeting which has state, lifecycle event componentDidMount() and render method.

class Greeting extends React.Component {
  constructor() {
    super();
    this.state = {
      name: "",
    };
  }

  componentDidMount() {
    // AJAX
    this.setState(() => {
      return {
        name: "William",
      };
    });
  }

  render() {
    return (
      <div>
        <h1 id="Hello-this-state-name">Hello! {this.state.name}</h1>
      </div>
    );
  }
}

At this time, the component is a stateful class component. In order to make Greeting a container component, we can split the UI into a display component, which will be explained below.

Display component


Display component uses props, render and context (stateless API), and since there is no need to use life cycle related APIs, you can use pure Functions to simplify describing them:

const GreetingCard = (props) => {
  return (
    <div>
      <h1 id="Hello-props-name">Hello! {props.name}</h1>
    </div>
  )
}

Display components only receive data and callbacks from props, which can be provided by their container components (parent components).

Detailed introduction to React component pattern (with examples)
The container component and the presentation component each encapsulate the data/logic and presentation parts into their own components:

const GreetingCard = (props) => {
  return (
    <div>
      <h1 id="props-name">{props.name}</h1>
    </div>
  )
}

class Greeting extends React.Component {
  constructor() {
    super();
    this.state = {
      name: "",
    };
  }

  componentDidMount() {
    // AJAX
    this.setState(() => {
      return {
        name: "William",
      };
    });
  }

  render() {
    return (
      <div>
       <greetingcard></greetingcard>
      </div>
    );
  }
}

如你所见,已经将 Greeting 组件中展示相关的部分移动到了它自己的函数式展示组件中。当然,这是一个非常简单的例子——对于更复杂的应用程序,这也是最基本的。

高阶组件

高阶组件是一种函数,它接受一个组件作为参数,然后返回一个新的组件。

这是一种可以对输入组件的 props 进行修改(增删改查)然后返回全新的修改后的组件强大模式,想想 react-router-v4 和 redux 。用了 react-router-v4 后,你可以使用 withRouter() 来继承以 props 形式传递给组件的各种方法。同样,用了redux,就可以使用 connect({})() 方法来将展示组件和 store 中的数据进行连接。

Detailed introduction to React component pattern (with examples)

代码演示:

import {withRouter} from 'react-router-dom';
class App extends React.Component {
  constructor() {
    super();
    this.state = {path: ''}
  }
  
  componentDidMount() {
    let pathName = this.props.location.pathname;
    this.setState(() => {
      return {
        path: pathName,
      }
    })
  }
  
  render() {
    return (
      <div>
        <h1 id="Hi-I-m-being-rendered-at-this-state-path">Hi! I'm being rendered at: {this.state.path}</h1>
      </div>
    )
  }
}

export default withRouter(App);

导出组件时,使用用 react-router-v4 的 withRouter()方法封装它。 在 组件 App 的生命周期事件 componentDidMount() 方法中,我们使用this.props.location.pathname 提供的值来更新 state。 由于我们使用了 withRouter 高阶组件,我们可以直接访问 this.props.locationlocation,而不需要直接将 location 作为 props 直接传入,非常方便。

渲染回调

与高阶组件类似,渲染回调或渲染 props 被用于共享或重用组件逻辑。虽然许多开发人员倾向于使用 高阶组件 的可重用逻辑,但是使用 渲染回调 仍然有一些非常好的理由和优势——这是在 Michael Jackson 的“永不写另一个高阶组件”中得到了最好的解释。简而言之,渲染回调减少了命名空间冲突,并更好的说明了逻辑来源。

Detailed introduction to React component pattern (with examples)

class Counter extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0,
    };
  }

  increment = () => {
    this.setState(prevState => {
      return {
        count: prevState.count + 1,
      };
    });
  };

  render() {
    return (
      <div>{this.props.children(this.state)}</div>
    );
  }
}

class App extends React.Component {
  render() {
    return (
      <counter>
        {state => (
          <div>
            <h1 id="The-count-is-state-count">The count is: {state.count}</h1>
          </div>
        )}
      </counter>
    );
  }
}

在 Counter 类中,在 render 方法中嵌入 this.props.children 并将 this.state 作为参数。在 App 类中,我们可以将我们组件封装在 Counter 组件中,因此我可以操作 Counter 组件内的逻辑。

Counter 组件的本质是暴露了 children 这个外部属性,将 children 具体的渲染细节交个 Counter 的使用者,使用的时候只需要将组件传入到 Counter 的 children 中,当然可以使用其他参数,如果 children 不够的话。

代码部署后可能存在的BUG没法实时知道,事后为了解决这些BUG,花了大量的时间进行log 调试,这边顺便给大家推荐一个好用的BUG监控工具 Fundebug。

The above is the detailed content of Detailed introduction to React component pattern (with examples). For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:segmentfault. If there is any infringement, please contact admin@php.cn delete
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

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

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),