Home > Web Front-end > JS Tutorial > Detailed introduction to React component pattern (with examples)

Detailed introduction to React component pattern (with examples)

不言
Release: 2019-02-21 17:45:15
forward
1992 people have browsed it

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>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>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>{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>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>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!

source:segmentfault.com
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template