Home  >  Article  >  Web Front-end  >  How does react work? A detailed introduction to the working principle of react

How does react work? A detailed introduction to the working principle of react

寻∝梦
寻∝梦Original
2018-09-11 11:33:085538browse

This article mainly talks about the working principle of react. The content includes the specific process of working principle. Now let us read this article together.

The most popular front-end frameworks now include AngularJS, React, Bootstrap, etc. Since I came into contact with ReactJS, the virtual DOM (Virtual DOM) and component-based development of ReactJs have deeply attracted me. Let’s experience the style of ReactJs with me~~ The article is a bit long, read it patiently, you will have a great understanding Harvest~

1. Introduction to ReactJS

React originated from Facebook’s internal project. Because the company was not satisfied with all the JavaScript MVC frameworks on the market, it decided to write its own one using Let’s set up the Instagram website. After making it, I found that this set of things is very useful, so it was open sourced in May 2013. Because the design idea of ​​React is extremely unique, it is a revolutionary innovation, has outstanding performance, and the code logic is very simple. Therefore, more and more people are beginning to pay attention to and use it, thinking that it may be the mainstream tool for web development in the future.

How does react work? A detailed introduction to the working principle of react

2. Understanding of ReactJS and the advantages of ReactJS

First of all, there are some misunderstandings about React. Let’s summarize them here:

  • React is not a complete MVC framework. It can be considered as the V (View) in MVC at most. Even React does not very much recognize the MVC development model;

  • React's server-side Render capability can only be regarded as an icing on the cake, not its core starting point. In fact, the official React website hardly mentions its application on the server side;

  • Someone takes React It is comparable to Web Component, but the two are not completely competitive. You can use React to develop a real Web Component;

  • React is not a new template language, JSX is just A representation that React can work without JSX.

1. Background and principles of ReactJS

In Web development, we always need to reflect changing data to the UI in real time. At this time, we need to modify the DOM operate. Complex or frequent DOM operations are usually the cause of performance bottlenecks (how to perform high-performance complex DOM operations is usually an important indicator of a front-end developer's skills). React introduces the virtual DOM (Virtual DOM) mechanism for this purpose: a set of DOM API is implemented on the browser side using Javascript. When developing based on React, all DOM construction is performed through virtual DOM. Whenever the data changes, React will rebuild the entire DOM tree. Then React compares the current entire DOM tree with the previous DOM tree to obtain the DOM structure. Difference, and then only the parts that need to change are updated in the actual browser DOM. And React can batch refresh the virtual DOM, in an event loop (Event Two data changes within the Loop will be merged. For example, if you continuously change the node content from A to B, and then from B to A, React will think that the UI has not changed at all, and if it is controlled manually, this This logic is usually extremely complex. Although a complete virtual DOM tree needs to be constructed every time, because the virtual DOM is memory data, the performance is extremely high, and only the Diff part is operated on the actual DOM, thus improving performance. In this way, while ensuring performance, developers no longer need to pay attention to how a certain data change is updated to one or more specific DOM elements, but only need to care about how the entire interface is rendered in any data state.

If you have written a pure Web page with server-side Rendering like you did in the 1990s, you should know that all the server-side has to do is render HTML based on the data and send it to the browser. If a certain status text needs to be changed due to a user click, this can also be done by refreshing the entire page. The server does not need to know which small piece of HTML has changed, but only needs to refresh the entire page based on the data. In other words, any UI changes are done through an overall refresh. React brings this development model to the front end in a high-performance way. Every time you update the interface, you can think that the entire page has been refreshed. As for how to perform partial updates to ensure performance, that is what the React framework has to do.

Borrowing the example of the chat application in Facebook’s video introducing React. When a new message comes, the traditional development idea is as shown above. Your development process needs to know which piece of data has come and how to convert the new DOM The node is added to the current DOM tree; and the development idea based on React is as shown below. You only need to care about the overall data. How the UI changes between the two data is completely left to the framework. It can be seen that using React greatly reduces the logic complexity, which means that development difficulty is reduced and there are fewer opportunities for bugs to occur.

2. Componentization

Virtual DOM (virtual-dom) not only brings simple UI development logic, but also brings the idea of ​​component development. The so-called component means encapsulation UI components with independent functions. React recommends rethinking the composition of the UI in the form of components, defining each module with relatively independent functions on the UI as a component, and then combining small components to form large components through nesting, and finally completing the construction of the overall UI. For example, Facebook's entire instagram.com site is developed using React. The entire page is one large component, which contains a large number of other nested components. If you are interested, you can take a look at the code behind it.

If the idea of ​​MVC allows you to separate the view-data-controller, then the componentized way of thinking brings about the separation between UI functional modules. Let’s look at the difference between MVC and component development ideas through a typical Blog comment interface.

For the MVC development model, developers define the three into different classes to achieve the separation of performance, data, and control. Developers split the UI more from a technical perspective to achieve loose coupling.

For React, it is a completely new idea. From a functional perspective, developers divide the UI into different components, and each component is packaged independently.

In React, you organize and write your code according to the natural division of interface modules. For the comment interface, the entire UI is a large component composed of small components, and each component only cares about itself. Parts of logic are independent of each other.

React believes that a component should have the following characteristics:

(1) Composable: A component is easy to use with other components, or nested within another component. If a component creates another component inside, then the parent component owns the child component it created. Through this feature, a complex UI can be split into multiple simple UI components;

( 2) Reusable: Each component has independent functions and can be used in multiple UI scenarios;

(3) Maintainable: Each small component only contains Its own logic is easier to understand and maintain;

2. Download ReactJS, write Hello, world

Downloading ReactJs is very simple. In order to facilitate everyone's downloading, here is the download address http://facebook.github.io/react/downloads.html. After the download is completed, what we see is a compressed package. After decompression, we create a new html file and reference the two js files react.js and JSXTransformer.js. The html template is as follows (change the js path to your own):

nbsp;html>
  
    <script></script>
    <script></script>
  
  
    <p></p>
    <script>
      // ** Our code goes here! **
    </script>
  

You may wonder here why the script type is text/jsx. This is because React’s unique JSX syntax is incompatible with JavaScript. Wherever JSX is used, type="text/jsx" must be added. Secondly, React provides two libraries: react.js and JSXTransformer.js, which must be loaded first. Among them, JSXTransformer.js is used to convert JSX syntax into JavaScript grammar. This step is time-consuming, and when it is actually online, it should be completed on the server. (If you want to see more, go to the PHP Chinese website React Reference Manual column to learn)

Here we can start writing code. First, let’s get to know each other first. Let’s take a look at the React.render method in ReactJs:

React.render is the most basic method of React, which is used to convert the template into HTML language and insert the specified DOM node.

Below we write code in the script tag to output Hello and world. The code is as follows:


React.render(        <h1>Hello, world!</h1>,
        document.getElementById('container')
      );


##Here It should be noted that react does not rely on jQuery. Of course, we can use jQuery, but the second parameter in render must use the JavaScript native getElementByID method, and jQuery cannot be used to select DOM nodes.

Then, when you open this page in the browser, you can see that the browser displays a big Hello, world, because we used the

tag.

Here, congratulations, you have entered the door of ReactJS~~Now, let us learn more about ReactJs~~

3. Jsx syntax

HTML language Written directly in the JavaScript language without any quotation marks, this is the syntax of JSX, which allows the mixing of HTML and JavaScript. If you know AngularJs, you will feel very familiar when you see the following code. Let's take a look at the code:

var names = ['Jack', 'Tom', 'Alice'];

      React.render(        <p>
        {
          names.map(function (name) {            return </p><p>Hello, {name}!</p>          })
        }        ,
        document.getElementById('container')
      );这里我们声明了一个names数组,然后遍历在前面加上Hello,输出到DOM中,输出结果如下:

How does react work? A detailed introduction to the working principle of react

#JSX allows inserting JavaScript variables directly into templates. If this variable is an array, all members of the array will be expanded. The code is as follows:

var arr = [        <h1>Hello world!</h1>,
        <h2>React is perfect!</h2>,      ];
      React.render(        <p>*{arr}*</p>,
        document.getElementById('container')
      );
The display result is as follows:

How does react work? A detailed introduction to the working principle of react

The asterisks here are just It is used for making logos, don’t be confused by her~~

If you see this, it means that you are quite interested in React. Congratulations, you persisted. Now, let’s start to learn about React. "Real Kungfu"~~ Are you ready?

 四、ReactJS组件

1、组件属性 

  前面说了,ReactJS是基于组件化的开发,下面我们开始来学习ReactJS里面的组件,React 允许将代码封装成组件(component),然后像插入普通 HTML 标签一样,在网页中插入这个组件。React.createClass 方法就用于生成一个组件类。

下面,我们来编写第一个组件Greet,有一个name属性,然后输出hello + name的值,代码如下:

var Greet = React.createClass({
        render: function() {          return <h1>Hello {this.props.name}</h1>;        }
      });

      React.render(        <greet></greet>,
        document.getElementById('container')
      );

看到这段代码,接触过AngularJS的朋友们是不是有一种熟悉的感觉,不过这里有几点需要注意:

  1、获取属性的值用的是this.props.属性名

  2、创建的组件名称首字母必须大写。

  3、为元素添加css的class时,要用className.

  4、组件的style属性的设置方式也值得注意,要写成style={{width: this.state.witdh}}

2、组件状态

  组件免不了要与用户互动,React 的一大创新,就是将组件看成是一个状态机,一开始有一个初始状态,然后用户互动,导致状态变化,从而触发重新渲染 UI 。下面我们来编写一个小例子,一个文本框和一个button,通过点击button可以改变文本框的编辑状态,禁止编辑和允许编辑。通过这个例子来理解ReactJS的状态机制。先看代码:

var InputState = React.createClass({
        getInitialState: function() {          return {enable: false};
        },
        handleClick: function(event) {          this.setState({enable: !this.state.enable});
        },
        render: function() {          
          return (            <p>
               <input>
               <button>Change State</button>
            </p>          );
        }
      });

      React.render(        <inputstate></inputstate>,
        document.getElementById('container')
      );

这里,我们又使用到了一个方法getInitialState,这个函数在组件初始化的时候执行,必需返回NULL或者一个对象。这里我们可以通过this.state.属性名来访问属性值,这里我们将enable这个值跟input的disabled绑定,当要修改这个属性值时,要使用setState方法。我们声明handleClick方法,来绑定到button上面,实现改变state.enable的值.效果如下:

How does react work? A detailed introduction to the working principle of react

原理分析:

   当用户点击组件,导致状态变化,this.setState 方法就修改状态值,每次修改以后,自动调用 this.render 方法,再次渲染组件。

这里值得注意的几点如下:

  1、getInitialState函数必须有返回值,可以是NULL或者一个对象。

  2、访问state的方法是this.state.属性名。

  3、变量用{}包裹,不需要再加双引号。

3、组件的生命周期  

组件的生命周期分成三个状态:

  • Mounting:已插入真实 DOM

  • Updating:正在被重新渲染

  • Unmounting:已移出真实 DOM

React 为每个状态都提供了两种处理函数,will 函数在进入状态之前调用,did 函数在进入状态之后调用,三种状态共计五种处理函数。

  • componentWillMount()

  • componentDidMount()

  • componentWillUpdate(object nextProps, object nextState)

  • componentDidUpdate(object prevProps, object prevState)

  • componentWillUnmount()

此外,React 还提供两种特殊状态的处理函数。

  • componentWillReceiveProps(object nextProps):已加载组件收到新的参数时调用

  • shouldComponentUpdate(object nextProps, object nextState):组件判断是否重新渲染时调用

下面来看一个例子:

 var Hello = React.createClass({
        getInitialState: function () {          return {
            opacity: 1.0
          };
        },

        componentDidMount: function () {          this.timer = setInterval(function () {            var opacity = this.state.opacity;
            opacity -= .05;            if (opacity 
              Hello {this.props.name}                      );
        }
      });

      React.render(        <hello></hello>,        document.body
      );

上面代码在hello组件加载以后,通过 componentDidMount 方法设置一个定时器,每隔100毫秒,就重新设置组件的透明度,从而引发重新渲染。

4、组件的嵌套

  React是基于组件化的开发,那么组件化开发最大的优点是什么?毫无疑问,当然是复用,下面我们来看看React中到底是如何实现组件的复用的,这里我们还写一个例子来说吧,代码如下:

var Search = React.createClass({
        render: function() {          return (            <p>
               {this.props.searchType}:<input>
               <button>Search</button>
            </p>          );
        }
      });      var Page = React.createClass({
        render: function() {          return (            <p>
               </p><h1>Welcome!</h1>
               <search></search>
               <search></search>
                      );
        }
      });
      React.render(        <page></page>,
        document.getElementById('container')
      );

这里我们创建了一个Search组件,然后又创建了一个Page组件,然后我们在Page组件中调用Search组件,并且调用了两次,这里我们通过属性searchType传入值,最终显示结果如图:

How does react work? A detailed introduction to the working principle of react

 五、ReactJs小结

关于ReactJS今天就先学习到这里了,下面来总结一下,主要有以下几点:

  1、ReactJs是基于组件化的开发,所以最终你的页面应该是由若干个小组件组成的大组件。

  2、可以通过属性,将值传递到组件内部,同理也可以通过属性将内部的结果传递到父级组件(留给大家研究);要对某些值的变化做DOM操作的,要把这些值放到state中。

  3、为组件添加外部css样式时,类名应该写成className而不是class;添加内部样式时,应该是style={{opacity: this.state.opacity}}而不是style="opacity:{this.state.opacity};"。

  4、组件名称首字母必须大写。

  5、变量名用{}包裹,且不能加双引号。

 六、ReactJS优缺点

优点:

React is very fast

Compared with other frameworks, React adopts a unique way of operating DOM.
It does not directly operate on the DOM.
It introduces a concept called virtual DOM, which is inserted between JavaScript logic and the actual DOM.
This concept improves web performance. During the UI rendering process, React implements local updates to the actual DOM through micro-operations in the virtual DOM.

Cross-browser compatibility
Virtual DOM helps us solve cross-browser problems. It provides us with a standardized API, which is no problem even in IE8.

Modularization
Write independent modular UI components for your program, so that when there is a problem with one or some components, you can easily isolate it.
Each component can be developed and tested independently, and they can introduce other components. This equates to improved code maintainability.
One-way data flow makes things clear
Flux is an architecture for creating a one-way data layer in JavaScript applications, which was conceptualized by Facebook along with the development of the React view library. It is just a concept, not an implementation of a specific tool. It can be absorbed by other frameworks. For example, Alex Rattray has a great Flux instance that uses Backbone's collections and models in React.
Pure JavaScript
Modern web applications work differently from traditional web applications.
For example, updates to the view layer require user interaction without requesting the server. So the view and controller are very dependent on each other.
Many frameworks use template engines such as Handlebars or Mustache to handle the view layer. But React believes that views and controllers should be interdependent rather than using third-party template engines, and, most importantly, it is a pure JavaScript program.
Isomorphic JavaScript

The biggest drawback of single-page JS applications is that they have great limitations on search engine indexing. React has a solution for this.
React can pre-render the application on the server and then send it to the client. It can restore the same record from pre-rendered static content into dynamic applications.
Because search engine crawlers rely on server-side responses rather than JavaScript execution, pre-rendering your application helps with SEO.
React has good compatibility with other frameworks/libraries
For example, RequireJS is used for loading and packaging, while Browserify and Webpack are suitable for building large applications. They make those difficult tasks less daunting.

shortcoming?

React itself is just a V, so if you want a complete framework for a large project, you may also need to introduce things related to Flux and routing.

Most pitfalls have not been stepped out

This article ends here (want to read For more information, go to the PHP Chinese website React User Manual column to learn). If you have any questions, you can leave a message below.

The above is the detailed content of How does react work? A detailed introduction to the working principle of 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