What is React?
What is React? Let’s take a look at the official description: a JavaScript library for building user interfaces.
React is an open source JavaScript framework for Facebook in 2013, so why did Facebook launch such a framework?
This comes from a bug generated by a requirement:
After the function was launched, there were always bugs. When the numbers of the three messages changed, too many operations could easily cause bugs. Can the bug be fixed? Can repair of course, but Facebook’s engineers are not satisfied with this, they began to think about why this problem, in traditional development mode, we have too much to the details of the interface (need to master and use a lot of the DOM API), the other about data (state), tend to be dispersed to various places, inconvenient management and maintenance.
They wondered if there might be a new model to solve these problems:
-
To divide functional modules as components
-
JSX describes what the UI looks like inside the component, and state stores the state inside the component
-
When the state of the application changes, you can use setState to modify the state. When the state changes, the UI will be automatically updated
The characteristics of the React
Declarative programming
- Declarative programming is the current paradigm for large front-end development
- It allows us to maintain only our own state. When the state changes, React renders our UI based on the latest state
Componentized development
Component-based development pages The current trend at the front end is to break down complex interfaces into smaller components
Multi-platform adaptation
- React launched in 2013 as a Web page development app;
- In 2015, Facebook launched ReactNative for mobile cross-platform development
- In 2017, Facebook launched ReactVR to develop virtual reality Web applications
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 into React code
The purpose of the three libraries is to make each library do its own thing. Before React 0.14, there was no concept of the React dom. All functions were contained in React. Why break it up? 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: React-DOM will render JSX into the real DOM and display it in the browser
- Native: React-DOM will talk about JSX rendering as a native control
Know the Babel
What is Babel?
Babel, or babel.js. Is the front end is used very widely editor, transfer. For example, many browsers do not support ES6 syntax, but ES6 syntax is very concise and convenient, and we want to use it when developing. Then we can write the source code using ES6, and then use the Babel tool to convert ES6 to the ES5 syntax that most browsers support.
React and Babel
React can be developed without Babel by default. However, if we write our own source code using react. createElement, the code is very cumbersome and unreadable. Then we could write JSX syntax directly and let Babel help us convert to React. CreateElement.
Introduce React dependencies
All three of these dependencies are essential when we write React code. You can add these three dependencies in the following way:
- Method 1: Direct CDN import
- Method 2: Add local dependencies
- Mode 3: Manage through NPM (use scaffolding later)
Through CDN, note the order of introduction. There is a crossorigin attribute whose purpose is to get error messages for cross-domain scripts
<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>
Copy the code
Use React to display a Hello World. When you write the React script, you must add type=”text/ Babel “to let Babel parse JSX syntax.
ReactDOM. Render function:
Parameter 1: Pass the content to be rendered. This content can be an HTML element or a React component
Parameter 2: Which HTML element to mount the rendered content to
Componentized development
We said that the first argument to reactdom. render is an HTML native or a component, so we can wrap the previous business logic into a component and pass it in as the first argument to the reactdom. render function.
How do you encapsulate a component in React?
Encapsulate components as classes
-
Define a class (class name capital, is the name of the component must be uppercase, lowercase can be considered as an HTML element), inherited from React.Com ponent
-
Implement the render function of the current component (render returns the JSX content that React will render later).
Data dependencies
Where is the data defined? The data in the component can be divided into two categories:
- Data participating in interface updates: When data variables are used, the content rendered by the component needs to be updated
- Data that does not participate in interface updates: When data variables are used, there is no need to update the content that will be rendered
The data that participates in the interface update can also be called the participation data flow, which is defined in the state of the current object.
- This can be done by specifying this. State = {defined data} in the constructor.
- When the data changes, you can call this.setState to update the data and tell React to update the data.
event
This in the event binding. Define a function directly in a class and bind it to an HTML native onClick event. Who does this currently point to?
The default is undefined. Oddly enough, it’s undefined; Because in normal DOM manipulation, when you listen for clicks, this in the listener function is actually a node object (such as a button object); Because React doesn’t render directly into the real DOM, the button we wrote was just a syntactic sugar, essentially a React Element object; So when we listen here, react binds our function to this, which by default is undefined;
If you want to use the current object in a bound function, such as this.setState, you need to get the this of the current object. You need to bind this directly to the function when it is passed, similar to the following: change the text
Know the JSX
What is the tag syntax for the assignment to the right of the element declaration?
It’s not a string (because it’s not wrapped in quotes), it looks like a piece of native HTML, but can we assign HTML directly to a variable in JS? This is not true. If we remove type=”text/ Babel “, we will get a syntax error; What is it? It’s actually a JSX syntax;
What is JSX?
- JSX is a JavaScript syntax eXtension, also known in many places as JavaScript XML because it looks like an XML syntax
- It is used to describe our UI interface, and its completion can be used in conjunction with JavaScript
Why React chose JSX
-
React argues that rendering logic is intrinsically coupled to other UI logic; For example, the UI needs to bind events (buttons, A native, etc.); For example, the UI needs to display data state, and when some state changes, the UI needs to be changed.
-
They are inseparable, so React doesn’t talk about separating tags into different files. Instead, it groups them together.
JSX writing specification
- The top level of JSX can only have one root element, so we often wrap a div primitive (or Fragment) around it;
- For ease of reading, we usually wrap a parenthesis () around JSX so that it is easy to read and JSX can be written on a new line;
- Labels in JSX can be single or double labels. (Note: for single tags, must end with />)
The use of the JSX
JSX embedded variables
-
Case 1: If the variable is Number, String, or Array, it can be displayed directly
-
Case 2: When the variable is null, undefined, or Boolean, the content is empty
-
Object type not valid as a React child
JSX embedded expression
-
Operational expression
-
Ternary operator
-
Execute a function
JSX binding properties
- For example, all elements have a title attribute
- For example, an img element would have a SRC attribute
- For example, the a element would have an href attribute
- For example, elements may need to be bound to a class
- Such as using inline style style natively
React Event binding
What if the native DOM native has a listening event?
- Method 1: obtain DOM native, add listening events;
- Method 2: In HTML native, directly bind onclick;
How does React work? There are two main differences in React event listening
- React events are named in a camelCase rather than pure lowercase
- You need to pass in an event handler with {} that will be executed when the event occurs
This binding problem
After the event is executed, we might need to get the attributes associated with the object of the current class. This is used in this case. If we print this, we will also find that it is undefined.
Why undefined?
The reason is that we don’t call the btnClick function actively, and React calls the btnClick function internally when the button changes. And when it calls internally, it doesn’t know how to bind the right this;
How to solve this problem?
Option 1: Bind to btnClick to show bind this
Scheme 2: Use ES6 Class Fields syntax
Scenario 3: Passing in arrow functions for event listening (recommended)
Event Parameter passing
When executing an event function, it is possible that we need to get some parameter information: for example, the event object, other parameters
- Case 1: Get the Event object
Many times we need to get the Event object to do something (such as prevent the default behavior)
If we don’t need this, we can just pass in the function to get the event object.
- Case two: Get more parameters
When we have more arguments, our best bet is to pass in an arrow function, an active event function, and pass in other arguments that are relevant;
React conditional rendering
In some cases, the content of the interface will display different content depending on the situation, or decide whether to render a part of the content:
In VUE, we control with commands: v-if, V-show; In React, all the conditional judgments are the same as normal JavaScript code;
What are the common methods of conditional rendering?
- Mode 1: Conditional statement
Suitable for more logical situations
- Method 2: ternary operator
Fit logic is relatively simple
- The and operator &&
Render a component if the condition is true. If the condition is not true, nothing is rendered;
React list rendering
In real development we would request a lot of data from the server, and the data would be stored in lists: songs, artists, chart lists; Data on items, shopping carts, and review lists; Such as friends’ messages, news feed, contact list data;
React does not have a V-for instruction like the Vue module syntax, and requires us to organize data into JSX through JavaScript code. Many students who transition from Vue to React are not used to it and think that Vue is more concise and clear. JSX in React works seamlessly with JavaScript, making it more flexible.
How do you present a list?
In React, the most common way to display lists is to use the map higher-order function for arrays;
Most of the time we need to do something with an array before we can show it:
For example, filter something out: the filter function
Take, for example, the slice function that snatches a portion of an array
We’ll notice in the previous code that whenever we present a list, we get a warning:
This warning tells us that we need to add a key to the JSX shown in the list.
The essence of the JSX
In fact, JSX is just react. createElement(Component, props,… The syntactic sugar of the children function. All JSX will eventually be converted to function calls to React. CreateElement.
CreateElement takes three arguments:
- Parameter 1: type
The current ReactElement type; If it is a tag element, use a string for “div”; If it is a component element, the name of the component is used;
- Parameter 2: config
All properties in JSX are stored in Config as properties and values of objects
- Parameter 3: Children
The contents of the tag are stored as an array of children; Of course, what about multiple elements? React processes them internally
Write JSX code directly
We’ll write our own react. createElement code:
We won’t be writing through JSX, and the interface will still render normally.
Also, in this case, do you need Babel content? Don’t need the
So, type=”text/ Babel “can be deleted;
So, we can delete it;
The virtual DOM creation process
We create a ReactElement object with React. CreateElement:
What does this ReactElement object do? Why did React create it?
- React uses the ReactElement object to form a JavaScript object tree;
- JavaScript’s object tree is known as the Virtual DOM;
How do I view the tree structure of ReactElement? We can print the previous JSX returns; Notice that I print JSX in the following code;
The resulting tree structure of ReactElement is the Virtual DOM
Why use the virtual DOM
Why use the virtual DOM instead of directly modifying the real DOM?
- It is difficult to track state changes: in the original development mode, it is difficult for us to track state changes, which is not convenient for debugging of our application;
- Low performance for manipulating the real DOM: Traditional development models tend to do a lot of DOM manipulation, which is very low performance;
DOM operation performance is very low:
- First, document.createElement itself creates a very complex object;
- Second, DOM manipulation can cause backflow and redrawing of the browser, so frequent DOM manipulation should be avoided in development.
Frequent manipulation of the DOM
Let’s take an example: let’s say we have an array to render: [0, 1, 2, 3, 4]. What do we do? We can show them by UL and LI.
Later, we added five more data: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
- Method 1: Iterate through the entire array (not recommended)
- Method 2: Add another 5 Li to ul
What about the performance of the above code? Very inefficient. Because we create the element with document.createElement and render it to the DOM with ul.appendChild(li), we do a lot of DOM manipulation; For batch operations, the best approach is not to modify the DOM again and again, but to merge the batch operations; (for example, merge with A DocumentFragment); We can use Virtual DOM to help us solve the above problems.
Declarative programming
The virtual DOM helps us move from imperative programming to declarative programming
React: The Virtual DOM is a programming concept.
In this concept, the UI is held in memory in an idealized or virtualized manner, and it is a relatively simple JavaScript object
We can sync the virtual DOM with the real DOM using reactdom.render, a process called Reconciliation.
This approach to programming gives React’s declarative API:
- You just tell React what state you want the UI to be;
- React to ensure that the DOM matches those states;
- You don’t need to do DOM manipulation directly, freeing yourself from manually changing the DOM, manipulating properties, and handling events;
The React of scaffolding
React Scaffolding itself relies on Node, so we need to install the Node environment
Official website: nodejs.org/en/download… After the installation, enter node -v on the command line to display the version to indicate that the installation is successful.
The last thing you need to install is the scaffolding to create the React project
npm install -g create-react-app
Create the React project
Now we can create the React project using scaffolding. Run the following command to create the React project: create-react-app Project name
Note: Project names cannot contain uppercase letters, and for more information on how to create projects, see GitHub’s Readme. Once created, go to the appropriate directory and start the project: NPM start
Directory structure analysis
Understand the PWA
The entire directory structure is pretty straightforward, except for one PWA-related concept:
- PWA stands for Progressive Web App, that is, Progressive Web application;
- A PWA application is a Web page, which can be written by Web technology.
- Then add App Manifest and Service Worker to realize PWA installation and offline functions.
- This form of Web existence is also called a Web App;
What problems does the PWA solve?
- Can be added to the main screen, click the main screen icon can realize the start animation and hide the address bar;
- Realize the offline cache function, even if the user’s mobile phone does not have the network, still can use some offline functions;
- Realizing message push; And a series of functions similar to Native App;
React componentization
Componentization is the core idea and focus of React. Componentization provides an abstraction that allows us to develop individual reusable components to construct our applications. Any application is abstracted into a tree of components.
Application of componentization:
- With the idea of componentization, we should make full use of it in future development.
- As much as possible, break the page up into small, reusable components.
- This makes our code easier to organize and manage, and also more extensible.
React components are more flexible and diverse than Vue components and can be divided into many classes in different ways:
- Components can be divided into: Functional Component (Functional Component) and Class Component (Class Component).
- Components can be divided into Stateless components and Stateful components according to whether there are Stateful components to be maintained.
- According to their different responsibilities, components can be divided into Presentational components and Container Components.
There is a lot of overlap between these concepts, but most of all they focus on the separation of data logic and UI presentation:
- Function components, stateless components, display components mainly focus on the display of UI;
- Class components, stateful components, container components focus on data logic;
Class components
The class component definition has the following requirements:
- Component names start with uppercase characters (whether class or function components)
- The class component needs to inherit from react.component
- The class component must implement the Render function
Before ES6, it was possible to use the create-React-class module to define class components. However, the current ES6 class definition is recommended.
Use class to define a component:
- Constructor is optional, and we usually initialize some data in constructor;
- This. State maintains the data inside our component;
- The Render () method is the only one that must be implemented in the class component;
The return value of the Render function
When render is called, it checks for changes to this.props and this.state and returns one of the following types:
- React elements: Usually created through JSX. For example,
React renders it as a DOM node, React renders it as a custom component; Whether it isReact elements again.
- Arrays or fragments: Enable the Render method to return multiple elements.
- Portals: The ability to render child nodes into different DOM subtrees.
- String or numeric types: They are rendered as text nodes in the DOM
- Boolean type or NULL: Render nothing
Function component
A function component is a function defined using function that returns the same thing as the render function in the class component. Functional components have their own characteristics:
- Does not have a life cycle, is updated and mounted, but does not have a life cycle function;
- No this(component instance);
- There is no internal state;
Let’s define a function component:
Know the life cycle
Many things have a whole process from creation to destruction. This process is called the life cycle. The React component also has its own life cycle. Understanding the life cycle of the component allows us to accomplish the desired functionality in the most appropriate place.
The relationship between lifecycle and lifecycle functions:
The life cycle is an abstract concept. The whole process of the life cycle is divided into many stages.
- Such as Mount, the process when a component is first rendered in the DOM tree;
- For example, Update, where the component state changes and the rendering process is updated.
- Such as Unmount, the process by which components are removed from the DOM tree;
React calls some of the functions we implement internally to tell us what phase we are in. These are called lifecycle functions:
- For example, implementing the componentDidMount function calls back when the component is already mounted to the DOM.
- For example, implementing the componentDidUpdate function calls back when the component has been updated;
- Implement the componentWillUnmount function that calls back when the component is about to be removed.
We can write our own logic code in these callback functions to accomplish our required functions. When we talk about the React lifecycle, we mainly talk about the class lifecycle, because functional components have no lifecycle functions;
Life cycle function
Constructor
If state is not initialized or method binding is not performed, there is no need to implement a constructor for the React component. Constructor usually does only two things:
- Initialize internal state by assigning the this.state object;
- Bind an instance of the event (this);
componentDidMount
ComponentDidMount () is called immediately after the component is mounted (inserted into the DOM tree). So where do you normally operate in componentDidMount?
- Dom-dependent operations can be performed here;
- This is the best place to send network requests; (Official recommendation)
- You can add some subscriptions here (which will be unsubscribed at componentWillUnmount);
componentDidUpdate
ComponentDidUpdate () is called immediately after the update, not the first rendering.
- This is where you can manipulate the DOM when the component is updated;
- If you compare the props before and after the update, you can also do the network request here; (For example, network requests are not executed when the props are not changed).
componentWillUnmount
ComponentWillUnmount () is called directly before the component is unmounted and destroyed.
- Perform the necessary cleanup operations in this method;
- For example, clear timers, cancel network requests or clear, subscriptions created in componentDidMount(), etc.;
Recognize nesting of components
Nested relationships exist between components:
If we had an application that put all of its logic in one component, that component would be very bloated and difficult to maintain; So the core idea of componentization should be to break up components into smaller components; These components are then assembled and nested together to form our application;
The nested logic above is as follows, and they have the following relationship:
- The App component is the parent of Header, Main, and Footer components.
- Main is the parent of Banner and ProductList.
Understand communication between components
During development, we often encounter the need for components to communicate with each other:
For example, the App may use multiple headers, and the contents of each Header are different. Then we need the user to pass some data to the Header for display. For example, if we request Banner data and ProductList data in Main at once, we need to pass them to display; It could also be that an event occurs in a child component that needs to be done by the parent, and the child needs to pass the event to the parent; In summary, in a React project, communication between components is very important;
Parent components pass child components – class components and function components
The parent component is presenting the child component and may pass some data to the child component:
- Parent components pass data to child components in the form of property = values;
- The child component uses the props parameter to get data from the parent component.
Child component passes parent component
In some cases, we also need a child component to pass a message to its parent:
In VUE this is done through custom events; In React, the parent component passes a callback function to the child component. This function is called in the child component.
Let’s complete an example here:
Disassemble counter cases; Encapsulate buttons in subcomponents: CounterButton; CounterButton clicks, passing content to the parent component to modify the value of counter;