search
HomeWeb Front-endJS TutorialDetailed interpretation of elements, components, instances and nodes in React

This article mainly introduces the elements, components, instances and nodes in React. Now I will share it with you and give you a reference.

The React in-depth series provides an in-depth explanation of the key concepts, features and patterns in React, aiming to help everyone deepen their understanding of React and use React more flexibly in their projects.

Elements, components, instances and nodes in React are four closely related concepts in React, and they are also four concepts that can easily confuse React beginners. Now, veteran cadres will introduce these four concepts in detail, as well as the connections and differences between them, to satisfy the curiosity of students who like to chew words and get to the bottom of things (veteran cadres are one of them).

Element

React element is actually a simple JavaScript object. A React element corresponds to a part of the DOM on the interface, describing the structure and structure of this part of the DOM. Rendering effect. Generally we create React elements through JSX syntax, for example:

const element = <h1 id="Hello-nbsp-world">Hello, world</h1>;

element is a React element. During the compilation process, the JSX syntax will be compiled into a call to React.createElement(). It can also be seen from the function name that the JSX syntax returns a React element. The compiled result of the above example is:

const element = React.createElement(
 &#39;h1&#39;,
 {className: &#39;greeting&#39;},
 &#39;Hello, world!&#39;
);

Finally, the value of element is a simple JavaScript object similar to the following:

const element = {
 type: &#39;h1&#39;,
 props: {
  className: &#39;greeting&#39;,
  children: &#39;Hello, world&#39;
 }
}

React elements can be divided into two categories: DOM type elements and An element of component type. DOM type elements use DOM nodes like h1, p, p, etc. to create React elements. The previous example is a DOM type element; component type elements use React components to create React elements, for example:

const buttonElement = <Button color=&#39;red&#39;>OK</Button>;

buttonElement is A component type element, its value is:

const buttonElement = {
 type: &#39;Button&#39;,
 props: {
  color: &#39;red&#39;,
  children: &#39;OK&#39;
 }
}

For DOM type elements, because they directly correspond to the DOM nodes of the page, React knows how to render. However, for component type elements, such as buttonElement, React cannot directly know what kind of page DOM the buttonElement should be rendered into. In this case, the component itself needs to provide DOM node information that React can recognize. The specific implementation method will be discussed when introducing the component. Detailed introduction.

With the React element, how should we use it? In fact, in most cases, we will not use React elements directly. React will automatically render the final page DOM based on the React elements. To be more precise, React elements describe the structure of React's virtual DOM, and React will render the real DOM of the page based on the virtual DOM.

Component (Component)

React component should be the most familiar concept in React. React uses the idea of ​​components to split the interface into reusable modules. Each module is a React component. A React application is composed of several components, and a complex component can also be composed of several simple components.

React components are closely related to React elements. The core function of React components is to return React elements. You may have questions here: shouldn't React elements be returned by React.createElement()? But the call of React.createElement() itself also requires a "person" to be responsible, and the React component is this "responsible person". The React component is responsible for calling React.createElement() and returning the React element for React to internally render it into the final page DOM.

Since the core function of a component is to return React elements, the simplest component is a function that returns React elements:

function Welcome(props) {
 return <h1 id="Hello-nbsp-props-name">Hello, {props.name}</h1>;
}

Welcome is a component defined with a function. If a component is defined using a class, the work of returning the React element is specifically borne by the render method of the component, for example:

class Welcome extends React.Component {
 render() {
  return <h1 id="Hello-nbsp-this-props-name">Hello, {this.props.name}</h1>;
 }
}

In fact, for components defined using a class, the render method is the only required method. Other components The life cycle methods are just for rendering and are not required.

Now consider the following example:

class Home extends React.Component {
 render() {
  return (
   <p>
    <Welcome name=&#39;老干部&#39; />
    <p>Anything you like</p>
   </p>
  )
 }
}

Home component uses the Welcome component, and the returned React element is:

{
 type: &#39;p&#39;,
 props: {
  children: [
   {
    type: &#39;Welcome&#39;,
    props: {
     name: &#39;老干部&#39;
    }
   },
   {
    type: &#39;p&#39;,
    props: {
     children: &#39;Anything you like&#39;
    }
   },
  ]
 }
}

For this structure, React knows how to render type = 'p' and type = 'p' nodes, but I don't know how to render the node with type='Welcome'. When React finds that Welcome is a React component (the judgment is based on the fact that the first letter of Welcome is capitalized), it will return according to the Welcome component. The React element determines how the Welcome node is rendered. The React element returned by the Welcome component is:

{
 type: &#39;h1&#39;,
 props: {
  children: &#39;Hello, 老干部&#39;
 }
}

This structure only contains DOM nodes, and React knows how to render. If this structure also contains other component nodes, React will repeat the above process and continue to parse the React elements returned by the corresponding components until the returned React elements only contain DOM nodes. This recursive process allows React to obtain the complete DOM structure information of the page, and the rendering work will naturally come naturally.

In addition, if you think about it carefully, you can find that the reuse of React components is essentially to reuse the React elements returned by this component. React elements are the most basic unit of React applications.

Instance

这里的实例特指React组件的实例。React 组件是一个函数或类,实际工作时,发挥作用的是React 组件的实例对象。只有组件实例化后,每一个组件实例才有了自己的props和state,才持有对它的DOM节点和子组件实例的引用。在传统的面向对象的开发方式中,实例化的工作是由开发者自己手动完成的,但在React中,组件的实例化工作是由React自动完成的,组件实例也是直接由React管理的。换句话说,开发者完全不必关心组件实例的创建、更新和销毁。

节点 (Node)

在使用PropTypes校验组件属性时,有这样一种类型:

MyComponent.propTypes = { 
 optionalNode: PropTypes.node,
}

PropTypes.node又是什么类型呢?这表明optionalNode是一个React 节点。React 节点是指可以被React渲染的数据类型,包括数字、字符串、React 元素,或者是一个包含这些类型数据的数组。例如:

// 数字类型的节点
function MyComponent(props) {
 return 1;
}

// 字符串类型的节点
function MyComponent(props) {
 return &#39;MyComponent&#39;;
}

// React元素类型的节点
function MyComponent(props) {
 return <p>React Element</p>;
}

// 数组类型的节点,数组的元素只能是其他合法的React节点
function MyComponent(props) {
 const element = <p>React Element</p>;
 const arr = [1, &#39;MyComponent&#39;, element];
 return arr;
}

// 错误,不是合法的React节点
function MyComponent(props) {
 const obj = { a : 1}
 return obj;
}

最后总结一下,React 元素和组件的概念最重要,也最容易混淆;React 组件实例的概念大家了解即可,几乎使用不到;React 节点有一定使用场景,但看过本文后应该也就不存在理解问题了。

上面是我整理给大家的,希望今后会对大家有帮助。

相关文章:

通过JS中利用FileReader如何实现上传图片前本地预览功能

根据select标签设置默认选中的选项方法该怎么做?

原生JavaScript中如何实现todolist功能

The above is the detailed content of Detailed interpretation of elements, components, instances and nodes in React. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

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.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

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.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

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.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

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.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

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

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

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: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

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 Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

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.

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version