ReactJs introductory tutorial that you can understand at a glance - the essence version

ReactJs introductory tutorial that you can understand at a glance - the essence version

[[141405]]

The most popular front-end frameworks now include AngularJS, React, Bootstrap, etc. Since I came into contact with ReactJS, I have been deeply attracted by its virtual DOM and component-based development. Let's appreciate the charm of ReactJs with me~~ The article is a bit long, please read it patiently, you will gain a lot~

1. Introduction to ReactJS

React originated from an internal project of Facebook. Because the company was not satisfied with all the JavaScript MVC frameworks on the market, it decided to write its own one to build the Instagram website. After it was completed, it was found to be very useful, so it was open sourced in May 2013. Because React's design concept is extremely unique, it is a revolutionary innovation, with outstanding performance and very simple code logic. Therefore, more and more people began to pay attention to and use it, believing that it may be the mainstream tool for Web development in the future.

ReactJS official website address: http://facebook.github.io/react/

Github address: https://github.com/facebook/react

2. Understanding of ReactJS and the advantages of ReactJS

First of all, there are some misunderstandings about React, which I will summarize here:

  • React is not a complete MVC framework. It can be considered as the V (View) in MVC at most. Even React does not fully recognize the MVC development model.
  • React's server-side rendering capability is just a nice-to-have feature, not its core purpose. In fact, the React official website barely mentions its server-side application.
  • Some people compare React and 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, and React can work without JSX.

1. Background and principles of ReactJS

In web development, we always need to reflect the changed data to the UI in real time, and then we need to operate the DOM. 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 introduced the virtual DOM mechanism for this purpose: a set of DOM APIs are implemented on the browser side using Javascript. When developing based on React, all DOM construction is performed through the virtual DOM. Whenever the data changes, React will rebuild the entire DOM tree, and then React will compare the current entire DOM tree with the previous DOM tree to get the difference in DOM structure, and then only perform actual browser DOM updates on the parts that need to be changed. Moreover, React can batch refresh the virtual DOM, and two data changes in an event 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. If it is controlled manually, this logic is usually extremely complicated. Although a complete virtual DOM tree needs to be constructed each time, the performance of the virtual DOM is extremely high because it is in-memory data, and only the Diff part is operated on the actual DOM, thus achieving the purpose of improving performance. In this way, while ensuring performance, developers will 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 under any data state.

If you have written pure web pages with server-side rendering like in the 1990s, you should know that all the server has to do is render HTML according to the data and send it to the browser. If a certain status text needs to be changed because of a user's click, it is also done by refreshing the entire page. The server does not need to know which small section of HTML has changed, but only needs to refresh the entire page according to the data. In other words, any change in the UI is completed by refreshing the whole page. React brings this development model to the front end in a high-performance way. Every time you update the interface, you can think of refreshing the entire page. As for how to perform local updates to ensure performance, it is what the React framework needs to accomplish.

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

2. Componentization

Virtual-DOM not only brings simple UI development logic, but also brings the idea of ​​component-based development. The so-called component is an encapsulated UI part with independent functions. React recommends rethinking the UI structure in a component-based way, defining each relatively independent module on the UI as a component, and then combining or nesting small components to form large components, and finally completing the construction of the overall UI. For example, Facebook's instagram.com is developed using React. The entire page is a 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 MVC idea allows you to separate the view, data, and controller, then the component-based thinking brings about the separation between UI functional modules. Let's take a typical blog comment interface to see the difference between MVC and component-based development ideas.

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

For React, it is a completely new idea. Developers divide the UI into different components from a functional perspective, and each component is independently encapsulated.

In React, you organize and write your code in a way that the interface modules are naturally divided. For the comment interface, the entire UI is a large component composed of small components. Each component only cares about its own part of the logic and is independent of each other.

React believes that a component should have the following characteristics:

  1. Composeable: A component can be easily used with other components or nested inside 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 contains only its own logic, which is easier to understand and maintain;
2. Download ReactJS and write Hello, world

ReactJs is very easy to download. For your convenience, here is the download address http://facebook.github.io/react/downloads.html. After downloading, we see 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):

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <script src= "build/react.js" ></script>
  5. <script src= "build/JSXTransformer.js" ></script>
  6. </head>
  7. <body>
  8. <div id= "container" ></div>
  9. <script type= "text/jsx" >
  10. // ** Our code goes here! **
  11. </script>
  12. </body>
  13. </html>

You may be wondering 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, the function of JSXTransformer.js is to convert JSX syntax to JavaScript syntax. This step is very time-consuming. When it is actually online, it should be completed on the server.

Now we can start writing code. First, let's get to know 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 it into the specified DOM node.

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

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

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

Then, open this page in the browser, and you can see that the browser displays a big Hello, world, because we used the <h1> tag.

At this point, congratulations, you have stepped into the door of ReactJS~~ Next, let's learn ReactJs further~~

#p# 3. Jsx syntax

The HTML language is written directly in the JavaScript language without any quotes. This is the syntax of JSX, which allows the mixing of HTML and JavaScript. If you have learned about AngularJs, you will feel very familiar with the following code. Let's look at the code:

  1. var names = [ 'Jack' , 'Tom' , 'Alice' ];
  2. React.render(
  3. <div>
  4. {
  5. names.map(function (name) {
  6. return <div>Hello, {name}!</div>
  7. })
  8. }
  9. </div>,
  10. document.getElementById( 'container' )
  11. );
Here we declare a names array, then traverse it and add Hello in front of it, and output it to the DOM. The output result is as follows:

JSX allows you to insert JavaScript variables directly into the template. If the variable is an array, all members of the array will be expanded. The code is as follows:

  1. var arr = [
  2. <h1>Hello world!</h1>,
  3. <h2>React is perfect!</h2>,
  4. ];
  5. React.render(
  6. <div>*{arr}*</div>,
  7. document.getElementById( 'container' )
  8. );

The results are as follows:

The asterisk here is just for identification, don't be confused by it~~

If you have read this far, it means you are quite interested in React. Congratulations, you have made it this far. Now, let’s start learning the real skills of React. Are you ready?

ReactJS components

1. Component properties

As mentioned before, ReactJS is based on component-based development. Now let's start learning the components in ReactJS. React allows you to encapsulate code into components and then insert the components into the web page like inserting ordinary HTML tags. The React.createClass method is used to generate a component class.

Next, let's write a component called Greet, which has a name attribute and outputs the value of hello + name. The code is as follows:

  1. var Greet = React.createClass({
  2. render: function() {
  3. return <h1>Hello { this .props.name}</h1>;
  4. }
  5. });
  6. React.render(
  7. <Greet name= "Jack" />,
  8. document.getElementById( 'container' )
  9. );

Seeing this code, friends who have been exposed to AngularJS may feel familiar, but there are a few points to note:

  1. To get the value of a property, use this.props.property name
  2. The first letter of the created component name must be capitalized.
  3. When adding a CSS class to an element, use className.
  4. It is also worth noting how the component's style attribute is set. It should be written as style={{width: this.state.witdh}}

2. Component status

Components inevitably need to interact with users. One of React's major innovations is to treat components as state machines. At the beginning, there is an initial state, and then user interaction causes the state to change, which triggers the re-rendering of the UI. Let's write a small example, a text box and a button. By clicking the button, you can change the editing state of the text box, prohibiting editing or allowing editing. Through this example, you can understand the state mechanism of ReactJS. Let's look at the code first:

  1. var InputState = React.createClass({
  2. getInitialState: function() {
  3. return {enable: false };
  4. },
  5. handleClick: function(event) {
  6. this .setState({enable: ! this .state.enable});
  7. },
  8. render: function() {
  9. return (
  10. <p>
  11. <input type= "text" disabled={ this .state.enable} />
  12. <button onClick={ this .handleClick}>Change State</button>
  13. </p>
  14. );
  15. }
  16. });
  17. React.render(
  18. <InputState />,
  19. document.getElementById( 'container' )
  20. );

Here, we use a method getInitialState again. This function is executed when the component is initialized and must return NULL or an object. Here we can access the property value through the this.state. property name. Here we bind the enable value to the disabled of the input. When you want to modify this property value, you need to use the setState method. We declare the handleClick method to bind it to the button to change the value of state.enable. The effect is as follows:

Principle analysis:

When the user clicks on a component, causing the state to change, the this.setState method modifies the state value. After each modification, the this.render method is automatically called to render the component again.

A few points worth noting here are as follows:

  1. The getInitialState function must have a return value, which can be NULL or an object.
  2. The way to access state is this.state.property name.
  3. Variables are enclosed in {} without double quotes.

#p#

3. Component life cycle

The component life cycle is divided into three states:

  • Mounting: Inserted into the real DOM
  • Updating: being re-rendered
  • Unmounting: Moved out of the real DOM

React provides two processing functions for each state. The will function is called before entering the state, and the did function is called after entering the state. There are a total of five processing functions for the three states.

  • componentWillMount()
  • componentDidMount()
  • componentWillUpdate(object nextProps, object nextState)
  • componentDidUpdate(object prevProps, object prevState)
  • componentWillUnmount()

In addition, React also provides two special state processing functions.

  • componentWillReceiveProps(object nextProps): called when the loaded component receives new parameters
  • shouldComponentUpdate(object nextProps, object nextState): Called when the component determines whether to re-render

Let's look at an example:

  1. var Hello = React.createClass({
  2. getInitialState: function () {
  3. return {
  4. opacity: 1.0
  5. };
  6. },
  7. componentDidMount: function () {
  8. this .timer = setInterval(function () {
  9. var opacity = this .state.opacity;
  10. opacity -= .05 ;
  11. if (opacity < 0.1 ) {
  12. opacity = 1.0 ;
  13. }
  14. this .setState({
  15. opacity: opacity
  16. });
  17. }.bind( this ), 100 );
  18. },
  19. render: function () {
  20. return (
  21. <div style={{opacity: this .state.opacity}}>
  22. Hello { this.props.name }
  23. </div>
  24. );
  25. }
  26. });
  27. React.render(
  28. <Hello name= "world" />,
  29. document.body
  30. );

After the hello component is loaded, the above code sets a timer through the componentDidMount method to reset the transparency of the component every 100 milliseconds, thereby triggering re-rendering.

4. Nesting of components

React is based on component-based development, so what is the biggest advantage of component-based development? Without a doubt, it is reuse. Let's take a look at how to reuse components in React. Here we will write an example. The code is as follows:

  1. var Search = React.createClass({
  2. render: function() {
  3. return (
  4. <div>
  5. { this .props.searchType}:<input type= "text" />
  6. <button>Search</button>
  7. </div>
  8. );
  9. }
  10. });
  11. var Page = React.createClass({
  12. render: function() {
  13. return (
  14. <div>
  15. <h1>Welcome!</h1>
  16. <Search searchType= "Title" />
  17. <Search searchType= "Content" />
  18. </div>
  19. );
  20. }
  21. });
  22. React.render(
  23. <Page />,
  24. document.getElementById( 'container' )
  25. );

Here we create a Search component, and then create a Page component. Then we call the Search component in the Page component and call it twice. Here we pass in the value through the attribute searchType, and the final result is shown in the figure:

5. ReactJs Summary

That’s all we have learned about ReactJS today. Let’s summarize it below. There are mainly the following points:

  1. ReactJs is based on component-based development, so ultimately your page should be a large component composed of several small components.
  2. You can pass values ​​into components through properties. Similarly, you can pass internal results to parent components through properties (left for your research). To perform DOM operations on changes in certain values, put these values ​​in the state.
  3. When adding external CSS styles to a component, the class name should be written as className instead of class; when adding internal styles, it should be style={{opacity: this.state.opacity}} instead of style="opacity:{this.state.opacity};".
  4. The first letter of the component name must be capitalized.
  5. Variable names are enclosed in {} and cannot be enclosed in double quotes.
6. References

React Chinese documentation http://reactjs.cn/

React Getting Started Tutorial http://www.ruanyifeng.com/blog/2015/03/react.html

Subversion front-end UI development framework: React http://www.infoq.com/cn/articles/subversion-front-end-ui-development-framework-react

<<:  Swift version of infinite loop carousel

>>:  The rise of HTML5 - not just an inspirational drama, but also a palace drama

Recommend

How to promote a new APP?

Mobile phone manufacturer cooperation bundling &l...

How do Japanese pubs generate private domain traffic?

Friends who often watch Japanese dramas will defi...

Summary of Zhihu promotion: 12 methods of marketing on Zhihu

1. Create topics that attract a lot of attention....

The latest guide to advertising after consumption upgrade!

When placing advertisements, many advertisers pre...

Detailed official interpretation of TikTok operations, policies, etc.!

After TikTok became popular, a large number of so...

An offline event planning and execution form to help you sort out your thoughts!

I have been collecting cases and organizing mater...

What knowledge do you need to learn to be a programmer?

Anyone who asks this question should be beaten, d...

How to attract traffic through Weibo search ranking?

There is an old saying that good wine needs no bu...

New US President's policy: Apple and Intel will have a hard time in China

According to CNNMoney, a financial website under ...

How to design a landing page that increases conversion rate by 30-50%? !

In the process of display advertising , when you h...

Analysis of Kuaishou’s user growth model!

Kuaishou has released its third-quarter 2021 fina...

Google Translate APP is banned! App Store rankings are rising rapidly.

Maybe everyone knows it. On March 29, Google upda...