Detailed introduction to React component pattern (with examples)
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.
render
state
props
context
- ##lifecycle events ##Although a component can use all of the above
, 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:
statefuland stateless.
- Stateful components usually use
- API
: render, state and life cycle related events.
Stateless components usually use - API
: render, props and context.
The above is why we want to introduce the
. 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 patternUsually there are the following component patterns:
- Container (container component)
- Presentational (display components)
- Higher order components (advanced components)
- Render callback (rendering callback)
"The container component just takes the data and then renders the child components" —— Jason Bonta
Container component is your data or logic layer and leverages the stateful API. Using lifecycle events, you can connect state to
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).
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 中的数据进行连接。
代码演示:
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 的“永不写另一个高阶组件”中得到了最好的解释。简而言之,渲染回调减少了命名空间冲突,并更好的说明了逻辑来源。
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!

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Linux new version
SublimeText3 Linux latest version

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

Dreamweaver Mac version
Visual web development tools

Atom editor mac version download
The most popular open source editor