React In-Depth Series 1: Elements, Components, Instances, and Nodes in React

Text: Xu Chao, author of "The Road to Advanced React"

Authorized to publish, reprint please indicate the author and source


React in-depth series, in-depth explanation of the key concepts, features and patterns in React, aims to help you deepen your understanding of React, and use React more flexibly in your projects.

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

Element

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

const element = <h1 className='greeting'>Hello, world</h1>;

element is a React element. In the compilation phase, 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 result of compiling the above example is:

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

Ultimately, the value of element is a simple JavaScript object like this:

const element = {
  type: 'h1',
  props: {
    className: 'greeting',
    children: 'Hello, world'
  }
}

React elements can be divided into two categories: DOM-type elements and component-type elements. DOM-type elements use DOM nodes like h1, div, 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='red'>OK</Button>;

buttonElement is an element of type component, and its value is:

const buttonElement = {
  type: 'Button',
  props: {
    color: 'red',
    children: 'OK'
  }
}

For DOM-type elements, React knows how to render them because they correspond directly to the DOM nodes of the page. However, for component-type elements, such as buttonElement, React cannot directly know which structure of page DOM should be rendered buttonElement. In this case, the component itself needs to provide DOM node information that React can recognize. The specific implementation method will be introduced when the component is introduced. Details.

With React elements, how should we use it? In fact, in most cases, we will not use React elements directly, and React will automatically render the final page DOM according to the React elements. More precisely, React elements describe the structure of React's virtual DOM, and React will render the page's real DOM based on the virtual DOM.

Component

React components should be the most familiar concept in React. React uses the idea of ​​components to split the interface into modules that can be reused, and 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 . Here you may have a question: shouldn't React elements be returned by React.createElement() ? But the invocation of React.createElement() itself also needs to be in charge of a "person", 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 render it into the final page DOM.

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

function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

Welcome is a component defined with functions. If you use a class to define a component, the work of returning React elements is specifically undertaken by the component's render method, for example:

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

In fact, using a class-defined component, the render method is the only required method, and the life cycle methods of other components are just for the render service and are not required.

Now consider the following example:

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

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

{
  type: 'div',
  props: {
    children: [
      {
        type: 'Welcome',
        props: {
          name: '老干部'
        }
      },
      {
        type: 'p',
        props: {
          children: 'Anything you like'
        }
      },
    ]
  }
}

For this structure, React knows how to render nodes of type = 'div' and type = 'p', but doesn't know how to render nodes of type = 'Welcome', when React finds that Welcome is a React component (the basis is Welcome first The letters are capitalized), which will decide how to render the Welcome node according to the React element returned by the Welcome component. The React element returned by the Welcome component is:

{
  type: 'h1',
  props: {
  	children: 'Hello, 老干部'
  }
}

This structure contains only DOM nodes, which React knows how to render. If this structure also contains other component nodes, React will repeat the above process and continue parsing the React elements returned by the corresponding components until the returned React elements only contain DOM nodes. Such a recursive process allows React to obtain the complete DOM structure information of the page, and the rendering work naturally comes 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 units of React applications .

Instance

The instance here refers specifically to the instance of the React component. A React component is a function or class that actually works with the instance object of the React component. Only after the component is instantiated, each component instance has its own props and state, and only holds references to its DOM nodes and child component instances. In the traditional object-oriented development method, the instantiation work is done manually by the developer, but in React, the instantiation work of the component is done automatically by React, and the component instance is also directly managed by React. In other words, developers don't have to care about creating, updating, and destroying component instances at all.

Node

When validating component properties using PropTypes, there is such a type:

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

What is the type of PropTypes.node? This indicates that optionalNode is a React node. React nodes are data types that can be rendered by React, including numbers, strings, React elements, or an array containing these types of data. E.g:

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

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

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

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

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

Finally, to sum up, the concepts of React elements and components are the most important and most likely to be confused; the concept of React component instances can be understood by everyone, but is hardly used; React nodes have certain usage scenarios, but they should not exist after reading this article. Understand the problem.

Next notice:

React In-Depth Series 2: Component Classification


New book recommendation "The Road to Advanced React"

Author: Xu Chao

Graduated from Zhejiang University with a master's degree, senior front-end engineer, long-term working in the energy Internet of things company Envision Intelligence. 8 years of software development experience, familiar with big front-end technology, rich experience in web front-end and mobile terminal development, especially in-depth understanding and practical experience of React technology stack and mobile Hybrid development technology.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325193896&siteId=291194637