1. Reasons for React

It’s official: a JavaScript library for building user interfaces

React is a framework that FaceBook opened source in 2013

1.2 Problems arising from using native development

  • Compatibility issues need to be addressed, which can be cumbersome, and too much compatibility code can lead to code redundancy
  • Not only the data and interaction in the interface, but also the frequent processing of the DOM in the page can be very tedious, and too much Reflow & Repaint can degrade the performance of the page
  • Data and code are too scattered and inconsistent, which is not conducive to code organization and maintenance, and is not conducive to good specification generation
  • In the traditional development mode, we have too much to operate the details of the interface (whether front-end, iOS, Android) and need to master and use a large number of DOM apis. Of course, we can simplify and adapt some APIS through jQuery
  • Data (state) tends to be scattered in various places and is not easy to manage and maintain

1.3 Benefits of React

  1. To divide functional modules as components
  2. Components injsxTo describe what the UI looks likestateTo store state within the component
  3. When the status of the application changes, passsetStateTo modify the state, the UI will automatically update when the state changes
  4. React does not have a V-for instruction like the Vue module syntax, and requires us to organize the data in JavaScript code into JSX sovueThere areinstructionBut moreWriting is simpleBut it doesn’tReacttheflexibilitySo high,ReactBecause there is no moreinstructionAnd its writing is all written inJavaScriptThe way to write, so it appearsMore flexibleBut in writing, it’s notvueMore tedious, yesJavaScript fundamentalsThe higher the requirements are

React features

2.1 Declarative programming

Requirement: a page with a Hello World and a button,

When the button is clicked, 'Hello World' changes to 'Hello React'Copy the code

Native JS - imperative programming

<p></p>
<button>Change the text</button>

<script>
    // Get the DOM node
    const pEl = document.querySelector('p')
    const btnEl = document.querySelector('button')

    // Initialize the text
    let content = 'Hello World'
    pEl.innerHTML = content


    // Set the click event
    btnEl.addEventListener('click'.() = > {
        content = 'Hello React'
        pEl.innerHTML = content
    })
</script>
Copy the code

Imperative programming: Each step tells the host environment a command

React implementation - Declarative programming

<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>

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

<script type="text/babel">
    let message = 'Hello World'

      function changeText() {
        message = 'Hello React'
          render()
      }

      function render() {
        ReactDOM.render( (
        <div>
          <p>{ message }</p>
          <button onClick={ changeText} >Change the text</button>
    </div>
      ), document.getElementById('app'))
      }

      render()
</script>
Copy the code

We only need to maintain our own state. When the state changes, React can render our UI based on the latest state

This type of programming paradigm is declarative programming

The figure above is a typical illustration of declarative programming

We can pre-define rules and methods for rendering interfaces (e.g., Vue, React, Angular)

We maintain our state (data) according to the defined rules

We can React or Vue the render function manually as long as we change the state

It rerenders the page according to predefined rules

2.2 Component development

Component-based development pages The current trend in the front end is to break down complex interfaces into smaller components

As shown above: This page is an App component that is then broken down into components based on small function points

Each component itself can also continue to be broken down into smaller components

These small components can then be combined to form a complete application

2.3 Multi-platform adaptation

  • React launched in 2013 as a Web page development app;
  • In 2015, Facebook launched ReactNative, a platform for mobile cross-platform development.
  • In 2017, Facebook launched ReactVR, a virtual reality Web application;

React development dependencies

3.1 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

Why did react-dom exist? There was no react-dom in the early versions of React

The React – DOM came into being with the birth of the React – Native

React 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 render JSX into native controls (such as Android Button, iOS UIButton).

Babel, also known as babel.js, is the most widely used front-end compiler

Basic functions of Babel

  1. Convert ES6 syntax to ES5 syntax that most browsers will recognize

    1. Write JSX (JavaScript XML) syntax directly, and let Babel help us convert component objects created in the form of react. createElement to React and react-DOM for parsing and rendering. By default, React development does not require Babel, but JSX is the react. createElement syntactically sugar, so JSX is usually used in development

3.2 Introducing the React dependency method

  • Method one: DirectIntroduced the CDN
  • Method 2: Download the file and add itRelying on local
  • Method 3: PassnpmManagement (subsequent use of scaffolding)

Before using scaffolding, the method of CDN introduction is temporarily used for introduction

<! Ubpkg is a front-end public CDN similar to bootCDN.
<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

Added: Crossorigin attribute

In the original case, we requested a cross-domain script, but there was an internal problem with the cross-domain script, and the error message could not be read locally

If a local attempt is made to log a Script error using window.onerror, a cross-domain Script will only return Script error

However, with the Crossorigin attribute enabled, cross-domain script error messages can also be obtained locally, but there are two prerequisites

  1. Cross-domain scripting servers must Allow the current domain name to obtain error information through the access-controll – allow-Origin header

  2. Crossorigin needs to be set on the tag (script, img, audio, video, etc.) that requests the cross-domain script, indicating that the SRC attribute on it supports cross-domain scripting

    When errors occur in the cross-domain script, detailed logs need to be printed

4. First experience with React

4.1 Hello World

<! -- this file exposes (exports) an object React --><script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script><! This file exposes an object named react-dom --><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>

<div id="app"></div><! To use JSX syntax, we need to declare type on the script tag to be text/ Babel --> <! Use this property to tell React that it was written in JSX and needs to be converted using Babel. JSX is an extension of javascript. Like Typescript,coffeeScript, JSX is a synthetical sugar of javascript.<script type="text/babel">
      // Note:
      // 1. Capitalize all three letters in ReactDOM

      // 2. Render is a method on ReactDOM used to render the interface
      // It takes three arguments
      // @param1: The content to render
      // @param2: mount object
      // @param3: callbeck to be executed after callback rendering.
      //

      // 3. React has only one root element
      // The first argument to render has one and only one root element (outermost element), which can have any number of child nodes

      The second argument to render specifies which DOM element to insert the template into, so we need to pass in the DOM node object
      // It is possible to obtain the corresponding DOM node by class or id
      // We usually use id to get the corresponding DOM node form
      
      // 5, the first argument to render can write both tags and components
      // The default render function overwrites the contents of the mounted object if there is some content in it
      ReactDOM.render(<h2>Hello World</h2>.document.getElementById('app'), () = > console.log('Render done'))
</script>
Copy the code

4.2 Modifying Data on the Page

Requirement: a page with a Hello World and a button,

When the button is clicked, 'Hello World' changes to 'Hello React'Copy the code

Written ES5

<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>

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

<script type="text/babel">
    // Initialize the data
    let msg = 'Hello World'

    // The button is bound by the event after the click
    function changeContent() {
       msg = 'Hello React'
      // The data is not immediately rerendered after modification
      // You need to call the render function again to update the data in the interface
      
      // In the actual development process, it is common to use ES6 class writing to define data
      Calling the render function manually is not recommended under any circumstances
       render()
     }

    // Define the render function
     function render() {
      ReactDOM.render((
       <main>
        <h2>{ msg }</h2>
        <button onClick={ changeContent} >change content</button>
    </main>
     ), document.getElementById('app'))}// The interface initializes rendering
     render()
</script>
Copy the code

Written ES6

<script src="./dist/react.development.js"></script>
<script src="./dist/react-dom.development.js"></script>
<script src="./dist/babel.min.js"></script>


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

<script type="text/babel">
    // Define App components
    class App extends React.Component {
        // Define class attributes in the constructor
        constructor() {
            // Call the parent constructor to initialize the parent class
            super(a)// React data is defined in state, which is an object
            this.state = {
                msg: 'Hello World'}}// Define the render function
        render () {
            // Return the result of the rendered content, i.e. the return value will be used as the first argument to render
            return (
                <main>{/* This is the way you comment in JSX */} {/* Use curly braces in React syntax to use variables note that it's curly braces, not mustache */}<div>{ this.state.msg }</div>{/* 1. When using methods in React, the event name uses a small hump. This is a function in React that encapsulates its native js function to a certain extent. Use curly braces to write js expressions or variables inside curly braces. Bind is used to change this to the current instance object when a function is called */}.<button onClick={ this.changeContent.bind(this) }>change content</button>
                </main>)}// When a React method is called, there is no way to get this when it is executed. This is not an instance of the current class
        // It will be called changeconten. call(undefined)
        changeContent() {
            // The setState method calls the render method to update the interface while modifying the state data
            // We no longer need to manually manipulate the DOM frequently
            this.setState({
                msg: 'Hello React'}}})// Render the interface
    // The first parameter here uses the App component defined earlier
    ReactDOM.render(<App />.document.getElementById('app'))
</script>
Copy the code

Add: when reading the clone repository on github, it is not recommended to read the master branch directly. Instead, use git checkout to checkout a specific tag and then read it

Since the master branch is the branch under development, the tag is a snapshot of the code, which is usually tagged at release time, so the code on the tag is the source code for a particular release

Git clone git git git git git git git git git git

git checkout tag_name 
Copy the code

However, Git might indicate that you are in a “detached HEAD” state.

Because a tag is a snapshot, you cannot change its code.

To make changes to the tag code, you need a branch:

git checkout -b branch_name tag_name
Copy the code

This will create a branch from the tag, and it will be normal Git operations.

React first Experience with React