React Series - Encounter React Development

1. Know React

1.1. What is React?

What is React? I believe that everyone who does front-end has more or less impressions of it.
Here we take a look at the official explanation of it: a JavaScript library for building user interfaces.

We know that for the front end, the main task is to build the interface, and building the interface is inseparable from three technologies:

  • HTML: Building the structure of the page
  • CSS: Styling the page
  • JavaScript: Page Dynamic Content and Interaction

So is it possible to build a complete user interface using the most native HTML, CSS, JavaScript? Of course you can, but there will be many problems

  • For example, the problem of operating DOM compatibility;
  • For example, the redundancy problem of too many compatible codes;
  • Such as code organization and specification issues;

Therefore, front-end developers have been in demand for more convenient JavaScript libraries:

  • For a long time in the past, jQuery was the most used JavaScript library;
  • In a past survey, 65% of the top 10,000 most visited websites in the world used jQuery, the most popular JavaScript library at the time;
  • But more and more companies are slowly moving away from using jQuery, including GitHub, where programmers use the most;

The three most popular frameworks in the front-end field are:

  • Vue
  • React
  • Angular

1.2. The origin of React

React was Facebook's open source JavaScript framework in 2013, so why did Facebook launch such a framework at that time?
This comes from a requirement, the resulting bug
After the feature goes live, there are always bug s:

  • When the numbers of the three messages change, too many operations can easily cause bug s;
  • In the traditional development mode, we go to the details of the operation interface too much; (front-end, iOS, Android)
    • For example, we need to master and use a large number of DOM APIs. Of course, we can simplify and adapt the use of some APIs through jQuery;
  • In addition, data (status) is often scattered in various places, which is inconvenient to manage and maintain;

They then think about whether there is a new model to solve the above problems:

  • 1. Divide each functional module in the way of components
  • 2. In the component, use jsx to describe the appearance of the UI, and use state to store the state in the component
  • 3. When the state of the application changes, use setState to modify the state. When the state changes, the UI will automatically update

1.3.1. Features of React

Declarative programming:

  • Declarative programming is the current mode of the entire front-end development: Vue, React, Flutter, SwiftUI;
  • It allows us to only maintain our own state, and when the state changes, React can render our UI interface according to the latest state;

Componentized development:

  • The current front-end trend of componentized development pages, we will talk about splitting complex interfaces into small components;
  • How to reasonably divide and design components is also a key point that I will talk about later;

Multi-platform adaptation:

  • In 2013, at the beginning of React's release, it was mainly to develop Web pages;
  • In 2015, Facebook launched ReactNative to develop mobile cross-platform; (Although Flutter is very popular at present, there are still many companies using ReactNative);
  • In 2017, Facebook launched ReactVR to develop virtual reality Web applications; (with the popularity of 5G, VR will also be a popular application scenario);

1.3.2. Advantages of React

React is updated and maintained by Facebook, and it is the crystallization of the ideas of a large number of excellent programmers:

  • The popularity of React is not limited to the recognition of it by ordinary developers, and a large number of other popular frameworks draw on the ideas of React;
  • At the beginning of the design of the Vue.js framework, a lot of inspiration came from Angular and React.
  • Including many new features of Vue3, it also draws on and learns React
  • For example React Hooks are groundbreaking new features (and the focus of our course)
    Vue Function Based API learns the idea of ​​React Hooks

A lot of Flutter's inspiration comes from React, a paragraph from the official website: (SwiftUI)

  • In fact, Widget - Element - RenderObject in Flutter corresponds to JSX - Virtual DOM - Real DOM

So React can be said to be the pioneer of the front-end, and it will always lead the trend of the entire front-end.

1.4. The current state of React

In addition, in HackerRank, there is a call in 2020, the framework (framework) you want to learn more:

Many well-known websites at home and abroad use React to develop:

At present, React is used more in large companies in China:

Hello React

2.1. Native case implementation

To walk through React, we can come up with a small requirement:

  • Display a text on the interface: Hello World
  • Click a button below, the text changes to Hello React when clicked
  • Display a text on the interface: Hello World
  • Click a button below, the text changes to Hello React when clicked

However, before we use React to implement, we will use native code to implement it, which is more convenient for everyone to compare React and native:

  • Of course, you can also use jQuery and Vue to implement, compare and learn them respectively

The native implementation code is as follows:

<body>
  
  <div class="app">
    <h2 class="title">Hello World</h2>
    <button class="change-btn">change text</button>
  </div>

  <script>
    // 1. Get the dom node
    const titleEl = document.getElementsByClassName("title")[0];

    // 2. Get data
    let message = "Hello World";

    // 3. Display the data into titleEl
    titleEl.innerHTML = message;

    // 4. Change the button content
    const btnEl = document.getElementsByClassName("change-btn")[0];
    btnEl.addEventListener('click', (e) => {
      message = "Hello React";
      titleEl.innerHTML = message;
    })
  </script>
</body>

2.2. React development dependencies

Developing React must rely on three libraries:

  • react: contains the core code necessary for react
  • react-dom: the core code required for react rendering on different platforms
  • babel: a tool to convert jsx to React code

The first contact with React will be confused by its cumbersome dependencies. For Vue, we only rely on a vue.js file, but react actually depends on three libraries.
In fact, these three libraries perform their own duties, and the purpose is to let each library simply do its own thing:

  • Before the 0.14 version of React, there was no concept of react-dom, and all functions were included in react.
  • Why split? The reason is react-native.
  • The react package contains the core code shared by react and react-native.
  • react-dom does different things for web and native:
    • web side: react-dom will say that jsx is finally rendered into a real DOM and displayed in the browser
    • Native side: react-dom will say that jsx is finally rendered into a native control (such as Button in Android, UIButton in iOS).

what is babel?

  • Babel, aka Babel.js.
  • It is a very widely used editor and transfer device in the front-end.
  • For example, many browsers currently do not support ES6 syntax, but ES6 syntax is very concise and convenient, and we hope to use it when developing.
  • Then we can use ES6 to write the source code, and then use the Babel tool to convert ES6 to ES5 syntax supported by most browsers.

The relationship between React and Babel:

  • By default, React can actually be developed without babel.
  • But the premise is that we use React.createElement to write the source code, which is very cumbersome and poorly readable.
  • Then we can directly write jsx (JavaScript XML) syntax, and let babel help us convert to React.createElement.
  • It will be discussed later;

Therefore, when we write React code, these three dependencies are essential.
So, how to add these three dependencies:

  • Method 1: Direct CDN introduction
    • React dependencies: https://unpkg.com/react@16/umd/react.development.js
    • react-dom dependency: https://unpkg.com/react-dom@16/umd/react-dom.development.js
    • babel dependency: https://unpkg.com/babel-standalone@6/babel.min.js
  • Method 2: After downloading, add local dependencies
  • Method 3: Manage through npm (subsequent scaffolding will be used again)

For the time being, we import directly through CDN to rehearse the following sample program:

  • There is a crossorigin attribute, the purpose of this attribute is to get the error information of cross-domain scripting
<script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>

2.3. Hello World

Let's take a look at how to use React development through a Hello World case.
The requirements are very simple: display a Hello World on the interface through React

  • Note: Here we write React script code, we must add type="text/babel", the function is to allow babel to parse the grammar of jsx
  <div id="app"></div>

  <script src="https://unpkg.com/react@16/umd/react.development.js"></script>
  <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
  <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>

  <script type="text/babel">
    // Rendering content through ReactDom objects
    ReactDOM.render(<h2>Hello World</h2>, document.getElementById("app"));
  </script>

Code analysis:

  • Dependencies don't need to be talked about, and three dependencies must be added to develop React code;
  • ReactDOM.render function:
    • Here we have defined a div with an id of app in advance
    • Here we pass in an h2 element, we will use the React component later
    • Parameter 1: Pass the content to be rendered, which can be an HTML element or a React component
    • Parameter 2: Which HTML element to mount the rendered content to

display effect:
But the content we render is currently defined, can we extract it into a variable?

  • Of course, we can introduce external variables or expressions through {} syntax
// define data into variables
let message = "Hello World";

// Rendering content through ReactDom objects
ReactDOM.render(<h2>{message}</h2>, document.getElementById("app"));

2.4. Hello React

According to our original case, we have implemented Hello World, but we want to change it to Hello React after clicking a button

2.4.1. The wrong way

The following code is our normal execution logic, but it will report an error:

  • The reason is that by default ReactDOM.render will overwrite everything in the native app that is mounted;
  • So after executing ReactDOM.render, there is no button native;
<body>
  
  <div id="app">
    <button class="change-btn">change text</button>
  </div>

  <script src="https://unpkg.com/react@16/umd/react.development.js"></script>
  <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
  <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>

  <script type="text/babel">
    // define data into variables
    let message = "Hello World";

    // Rendering content through ReactDom objects
    ReactDOM.render(<h2>{message}</h2>, document.getElementById("app"));

    // get btn
    const btnEl = document.getElementsByClassName("change-btn")[0];
    btnEl.addEventListener("click", (e) => {
      console.log(e);
    })
  </script>
</body>

2.4. Hello React

According to our original case, we have implemented Hello World, but we want to change it to Hello React after clicking a button

2.4.1. The wrong way

The following code is our normal execution logic, but it will report an error:
The reason is that by default ReactDOM.render will overwrite everything in the native app that is mounted;
So after executing ReactDOM.render, there is no button native;

<body>
  
  <div id="app">
    <button class="change-btn">change text</button>
  </div>

  <script src="https://unpkg.com/react@16/umd/react.development.js"></script>
  <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
  <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>

  <script type="text/babel">
    // define data into variables
    let message = "Hello World";

    // Rendering content through ReactDom objects
    ReactDOM.render(<h2>{message}</h2>, document.getElementById("app"));

    // get btn
    const btnEl = document.getElementsByClassName("change-btn")[0];
    btnEl.addEventListener("click", (e) => {
      console.log(e);
    })
  </script>
</body>

2.4.2. The right way

Although it can be achieved, the smoothness of the entire code is too cumbersome

<body>
  
  <div id="app">
  </div>

  <script src="https://unpkg.com/react@16/umd/react.development.js"></script>
  <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
  <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>

  <script type="text/babel">
    // define data into variables
    let message = "Hello World";

    // Rendering content through ReactDom objects
    render();

    // define a function to execute
    function btnClick() {
      message = "Hello React";
      render();
    }

    function render() {
      ReactDOM.render((
        <div>
          <h2>{message}</h2>
          <button onClick={btnClick}>change text</button>
        </div>
      ), document.getElementById("app"));
    }
  </script>
</body>

2.4.3. The way of components

The whole logic can actually be regarded as a whole, then we can encapsulate it into a component:

  • We said that the first parameter of ReactDOM.render is an HTML native or a component;
  • So we can first encapsulate the previous business logic into a component, and then pass it into
    The first parameter in the ReactDOM.render function;

In React, how to encapsulate a component?

  • Here we temporarily use classes to encapsulate components:
    The jsx content returned in render is the content that React will help us render later
    1. Define a class that inherits from React.Component
    2. Implement the render function of the current component

The specific code is as follows:

class App extends React.Component {
  render() {
    return (<h2>Hello World</h2>)
  }
}

ReactDOM.render(<App/>, document.getElementById("app"));

What if our Hello World was variable dependent and would change based on button clicks? Several core points are involved here

1. Where is the data defined

  • The data in the component, we can divide it into two categories:

    • Data involved in interface update: When the data is variable, the content rendered by the component needs to be updated
    • Data that does not participate in interface updates: when the data is variable, there is no need to update the content that will make up the rendering
  • The data participating in the interface update can also be called participating in the data flow. This data is defined in the state of the current object.

    • We can pass this.state = {defined data} in the constructor
  • When our data changes, we can call this.setState to update the data and notify React to update

    • When the update operation is performed, the render function is called again, and the latest data is used to render the interface

2. this in event binding

  • Define a function directly in the class, and bind this function to the native onClick event of html. Who does this function currently point to?

  • undefined by default

    • Very strange, it is undefined;
    • Because in normal DOM operations, listening for clicks, this in the listening function is actually a node object (for example, a button object);
    • This time, because React is not directly rendered into a real DOM, the button we wrote is just a syntactic sugar, and its essence is the Element object of React;
    • Then when listening occurs here, the this bound by react to our function is undefined by default;
  • In the bound function, we may want to use the current object, such as executing the this.setState function, we must get the this of the current object

    • We need to directly bind this function to this function when passing in a function
    • Similar to the following writing: change text

Let's take a look at how the code is implemented:

class App extends React.Component {
  constructor() {
    super();
    this.state = {
      message: "Hello World"
    };
  }

  render() {
    return (
      <div>
        <h2>{this.state.message}</h2>
        <button onClick={this.changeText.bind(this)}>change text</button>
     </div>
    )
  }

  changeText() {
    this.setState({
      message: "Hello React"
    })
  }
}

ReactDOM.render(<App/>, document.getElementById("app"));

Tags: React

Posted by mtombs on Mon, 30 May 2022 08:47:55 +0530