Table of Contents
Hello! {this.state.name}
Hello! {props.name}
{props.name}
Hi! I'm being rendered at: {this.state.path}
The count is: {state.count}
Home Web Front-end JS Tutorial Detailed introduction to React component pattern (with examples)

Detailed introduction to React component pattern (with examples)

Feb 21, 2019 pm 05:45 PM
javascript react.js front end programmer

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>
    );
  }
}
Copy after login

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>
  )
}
Copy after login

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>
    );
  }
}
Copy after login

如你所见,已经将 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);
Copy after login

导出组件时,使用用 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>
    );
  }
}
Copy after login

在 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 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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

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)

Which AI programmer is the best? Explore the potential of Devin, Tongyi Lingma and SWE-agent Which AI programmer is the best? Explore the potential of Devin, Tongyi Lingma and SWE-agent Apr 07, 2024 am 09:10 AM

On March 3, 2022, less than a month after the birth of the world's first AI programmer Devin, the NLP team of Princeton University developed an open source AI programmer SWE-agent. It leverages the GPT-4 model to automatically resolve issues in GitHub repositories. SWE-agent's performance on the SWE-bench test set is similar to Devin, taking an average of 93 seconds and solving 12.29% of the problems. By interacting with a dedicated terminal, SWE-agent can open and search file contents, use automatic syntax checking, edit specific lines, and write and execute tests. (Note: The above content is a slight adjustment of the original content, but the key information in the original text is retained and does not exceed the specified word limit.) SWE-A

PHP and Vue: a perfect pairing of front-end development tools PHP and Vue: a perfect pairing of front-end development tools Mar 16, 2024 pm 12:09 PM

PHP and Vue: a perfect pairing of front-end development tools. In today's era of rapid development of the Internet, front-end development has become increasingly important. As users have higher and higher requirements for the experience of websites and applications, front-end developers need to use more efficient and flexible tools to create responsive and interactive interfaces. As two important technologies in the field of front-end development, PHP and Vue.js can be regarded as perfect tools when paired together. This article will explore the combination of PHP and Vue, as well as detailed code examples to help readers better understand and apply these two

Revealing the appeal of C language: Uncovering the potential of programmers Revealing the appeal of C language: Uncovering the potential of programmers Feb 24, 2024 pm 11:21 PM

The Charm of Learning C Language: Unlocking the Potential of Programmers With the continuous development of technology, computer programming has become a field that has attracted much attention. Among many programming languages, C language has always been loved by programmers. Its simplicity, efficiency and wide application make learning C language the first step for many people to enter the field of programming. This article will discuss the charm of learning C language and how to unlock the potential of programmers by learning C language. First of all, the charm of learning C language lies in its simplicity. Compared with other programming languages, C language

Questions frequently asked by front-end interviewers Questions frequently asked by front-end interviewers Mar 19, 2024 pm 02:24 PM

In front-end development interviews, common questions cover a wide range of topics, including HTML/CSS basics, JavaScript basics, frameworks and libraries, project experience, algorithms and data structures, performance optimization, cross-domain requests, front-end engineering, design patterns, and new technologies and trends. . Interviewer questions are designed to assess the candidate's technical skills, project experience, and understanding of industry trends. Therefore, candidates should be fully prepared in these areas to demonstrate their abilities and expertise.

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Is Django front-end or back-end? check it out! Is Django front-end or back-end? check it out! Jan 19, 2024 am 08:37 AM

Django is a web application framework written in Python that emphasizes rapid development and clean methods. Although Django is a web framework, to answer the question whether Django is a front-end or a back-end, you need to have a deep understanding of the concepts of front-end and back-end. The front end refers to the interface that users directly interact with, and the back end refers to server-side programs. They interact with data through the HTTP protocol. When the front-end and back-end are separated, the front-end and back-end programs can be developed independently to implement business logic and interactive effects respectively, and data exchange.

Exploring Go language front-end technology: a new vision for front-end development Exploring Go language front-end technology: a new vision for front-end development Mar 28, 2024 pm 01:06 PM

As a fast and efficient programming language, Go language is widely popular in the field of back-end development. However, few people associate Go language with front-end development. In fact, using Go language for front-end development can not only improve efficiency, but also bring new horizons to developers. This article will explore the possibility of using the Go language for front-end development and provide specific code examples to help readers better understand this area. In traditional front-end development, JavaScript, HTML, and CSS are often used to build user interfaces

Django: A magical framework that can handle both front-end and back-end development! Django: A magical framework that can handle both front-end and back-end development! Jan 19, 2024 am 08:52 AM

Django: A magical framework that can handle both front-end and back-end development! Django is an efficient and scalable web application framework. It is able to support multiple web development models, including MVC and MTV, and can easily develop high-quality web applications. Django not only supports back-end development, but can also quickly build front-end interfaces and achieve flexible view display through template language. Django combines front-end development and back-end development into a seamless integration, so developers don’t have to specialize in learning

See all articles