[react] basics --- jsx array project construction class components, function components, component value transfer, event binding, event parameter state

  • vscode install react development extension

1, React first acquaintance

Multiple dependency files need to be introduced for react development, among which react.js and react-dom.js are the dependency files that we must introduce to create react applications.

  • react.js(https://unpkg.com/react@16/umd/react.development.js)

    • Core, which provides functions such as creating elements and components
  • react-dom.js(https://unpkg.com/react-dom@16/umd/react-dom.development.js)

    • Provides DOM related functions

Note: About react external js file

  • If you need another version later, you can go to it yourself
  • The files found on the Internet (including those distributed by us) may be incompletely downloaded. If this happens, it is recommended to download them again

Download the JS class library files of the corresponding react.js and react-dom.js development versions to the local machine, and then import them into the current web page through the script tag of HTML, as follows (when importing the corresponding JavaScript files, you need to pay attention to the order, first introduce the core files, and then other files):

// Core library of React
<script src="js/react.development.js"></script>
//DOM related functions
<script src="js/react-dom.development.js"></script>

Define the reactjs rendering container id in HTML and perform operations related to React instantiation to complete the display of helloworld:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title>React study</title>
        <meta
            name="viewport"
            content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no"
        />
    </head>
    <body>
        <div id="app"></div>
        <!-- introduce react Related documents -->
        <script src="./js/react.development.js"></script>
        <script src="./js/react-dom.development.js"></script>
        <script>
            // Create virtual dom
            // React.createelement (tag name, DOM attribute information in object form, content in DOM / sub DOM)
            // React.createelement (tag name, DOM attribute information in object form, content / sub DOM in DOM, content / sub DOM in DOM,...)
            // React.createelement (tag name, DOM attribute information in object form, [content in DOM / sub DOM, content in DOM / sub DOM,...])
            const vNode = React.createElement("div", {}, "hello world");
            // Get mount point
            const el = document.getElementById("app");
            // Reactdom.render (virtual DOM, mount point)
            ReactDOM.render(vNode, el);
        </script>
    </body>
</html>

It should be noted that in react, if the class attribute operation of DOM is involved in the JavaScript code, please do not use class directly, because this class is a keyword in es6, and className needs to be used to replace it in react. Therefore, examples are as follows:

const vNode = React.createElement("div", {id: "hi",className: "cls"}, "hello world");

2, JSX

1. Overview

Because the React element created by the React.createElement() method has some problems, the code is cumbersome, the structure is not intuitive, the described structure cannot be seen at a glance, it is not elegant, and writing code during development is very unfriendly.

React uses JSX to replace conventional JavaScript. JSX can be understood as an extension of JavaScript syntax. The tag declaration in it should meet the requirements of XML specification. React does not have to use JSX, but it has the following advantages:

  • JSX executes faster because it is optimized after compiling into JavaScript code

  • It is type safe and errors can be found during compilation

  • Declarative syntax is more intuitive and has the same structure as HTML, which reduces the learning cost and improves the development efficiency

  • There must be a top-level element package in jsx syntax (a major feature of XML), otherwise the compilation will report an error and the program will not run

2. JSX refactoring Hello world

The quickest way to try JSX in the project is to add this < script > tag to the page and introduce the babel class library for parsing JSX syntax. Note that if JSX syntax is used in the subsequent < script > tag block, you must declare the type="text/babel", otherwise babel will not parse JSX syntax.

<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>

Refactoring hello world Code:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title>Examples</title>
        <meta
            name="viewport"
            content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no"
        />
    </head>
    <body>
        <div id="app"></div>
        <!-- introduce react Related documents -->
        <script src="./js/babel.min.js"></script>
        <script src="./js/react.development.js"></script>
        <script src="./js/react-dom.development.js"></script>
        <!-- script Be sure to write it on the label type="text/babel" -->
        <script type="text/babel">
            // Create virtual dom
            const vNode = <div>hello world</div>;
            // const vNode = (<div>hello world</div>);
            // Get mount point
            const el = document.getElementById("app");
            // Page rendering
            ReactDOM.render(vNode, el);
        </script>
    </body>
</html>

3. js expressions in JSX syntax

3.1. Embed JS expression

In JSX syntax, to write JS code to {}, all tags must be closed. ({} it feels like an interpolation expression in vue)

let num = 100;
let bool = false;

// JSX syntax
var vNode = (
    <div>
        {/* I'm a comment */}
        {num}
        <hr />
        {/* Ternary operation */}
        {bool ? "Condition is true" : "Condition is false"}
    </div>
);

ReactDOM.render(vNode, document.getElementById("app"));

3.2. Attribute binding src={src}

Benchmarking: Vue's v-bind instruction

const src = "http://www.mobiletrain.org/images/index/new_logo.png";
const style = { fontSize: "20px", color: "red" };
const html = "<a href='http://Www.baidu. Com '> Baidu < / a > ";

// Get element
const app = document.getElementById("app");
// Create virtual DOM
const vNode = (
    <div>
        { /*If the attribute of the tag needs to be parsed by JSX, the value of the attribute cannot be quoted*/ }
        <img src={src} />
        <hr/>
        <p style={style}>The three Beichuan earthquakes were the aftershocks of Wenchuan earthquake</p>
        <hr/>
        <p className="cl1">iPhone12 Sale queue</p>
        { /*
             Output HTML string (understand)
             Note: react does not parse html strings by default
             The reason is: security issues
             If you really want to output the parsed html string, follow the following syntax
        */ }
        <p dangerouslySetInnerHTML={{__html:html}}></p>
    </div>
);
// Render Page 
ReactDOM.render(vNode, app);

3.3 array rendering

3.3.1 direct rendering

let arr = ["Zhang San", "Li Si", "Wang Wu", "Luo Xiang"];
// Get mount point
const el = document.getElementById("app");
// Create virtual DOM
const vNode = (
    <div>
        {/* Direct output data */}
        {arr}
    </div>
);
// Render
ReactDOM.render(vNode, el);

The results of the above outputs are as follows:

3.3.2 processing and rendering

let arr = ["Zhang San", "Li Si", "Wang Wu", "Luo Xiang"];
// Get mount point
const el = document.getElementById("app");
// Create virtual DOM
const vNode = (
    <div>
        {/* Process and render */}
        <ul>
            {/* Wrap the circulation body with a layer of {}, otherwise it will be wrong */}
            {
                arr.map((item, index) => {
                    return <li key={index}>{item}</li>;
                })
            }
            <hr />
            {
                /* 
                Wrap the circular body with a layer of {}. If you don't wrap it, it will be wrong. If you wrap the circular body, it will be 1 line
            	{}And return can be omitted (arrow function)
            	*/
            }
            {
                arr.map((item, index) => (
                    <li key={index}>{item}</li>
                ))
            }
        </ul>
    </div>
);
// Render
ReactDOM.render(vNode, el);

3, Project construction

The React team recommends using create React app (equivalent to vue cli of vue) to create a new single page application project of React, which provides a modern build setting with zero configuration.

Significance of create React app:

  • The scaffold is officially provided with zero configuration and can be used without manual configuration and cumbersome tools

  • Make full use of Webpack, Babel, ESLint and other tools to assist project development

  • Focus on business, not tool configuration

Create react app will configure our development environment so that we can use the latest JavaScript features, provide a good development experience, and optimize your application for the production environment. In order to successfully use the create react app scaffold, we need to install node > = 8.10 and NPM > = 5.6 on our machine.

1. Initialize project

Use the following command in the terminal to build the react project:

npx create-react-app my-app
# The above installation method does not require global installation of create react app. If global installation is required, you can execute the following command
# npm i -g create-react-app
# create-react-app your-app

It may take a long time to create a project. After the project is created, you can execute the following instructions:

# Enter project directory
cd my-app
# Start project
npm start

Tip: if yarn (a package management tool owned by Facebook, similar to npm) is installed on this machine, the project start command prompt given after installation is yarn start.

2. Directory structure

After understanding the directory structure of react, you can clean up the files of the initialized projects. Here, you can delete all the contents in the srcy and public directories. If you need to write your own contents later.

4, Components

Component allows us to split the UI into independent reusable code fragments and conceive each fragment independently. Conceptually, it is similar to JavaScript function, which accepts arbitrary props and returns the React element (JSX) used to describe the display content of the page.

1. How components are created

1.1. Function creation component

Components created by functions have the following characteristics:

  • Function component (stateless component): use JS functions to create components
  • Function names start with uppercase letters (recommended)
  • A function component must have a return value indicating the structure of the component (virtual DOM), and the content must have a top-level element

For example, create a new component file src/App.jsx:

Convention: the component suffix can be. js or. jsx. In order to distinguish the business code of components and projects, it is recommended to use. jsx for components and. js for business code suffix.

import React from 'react'
// Function names must be capitalized
function App() {
    return (
        <div>This is the first function component</div>
    )
}

export default App;

To output the effect, you can create the project entry file src/index.js:

import React from "react";
import ReactDOM from "react-dom";

import App from "./App";

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

Note that since the project has been cleaned up before, there is no mount point in the current project, so you need to create an HTML file index.html under public / and set a mount location in its body:

<div id="root">
    
</div>

1.2 class I components

Class components have the following characteristics:

  • Components created using class of ES6 syntax (stateful components)

  • Class names start with uppercase letters (recommended)

  • Class component should inherit the parent class of React.Component, so you can use the methods or properties provided in the parent class

  • Class component must provide render method for page structure rendering. The structure must have top-level elements and must return

import React from "react";
// Create a class class, inherit React.Component, provide render method in it, and return content in return
class App extends React.Component {
    render() {
        return <div>This is the first class component</div>;
    }
}

export default App;

In addition to the above writing method, you can also import React.Component on demand in the following form:

// Introduce react and Component
import React,{Component} from "react";

// Class component
class App extends Component {
    render() {
        return <div>This is the first class component</div>;
    }
}

// export
export default App;

2. Component value transfer

The value is transferred between components. In React, the data transfer is completed through the read-only attribute props.

props: accept any input parameter and return the React element used to describe the content of the page display.

2.1 function components

Function components pass values using props: pass props parameters to functions in the form of formal parameters.

For example, there is a sub component src/Components/Item.jsx, and the code is as follows:

import React from "react";

const Item = (props) => {
    return (
        <div>
            The sea embraces all rivers, and tolerance is great,{props.next}.  -- {props.name}
        </div>
    );
};

export default Item;

To pass the name and next values to the parent component, the parent component src/App.jsx can be written as:

import React from "react";

import Item from "./Components/Item";

class App extends React.Component {
    render() {
        return <Item name="Lin Zexu" next="Standing on a thousand walls, you are just like a man without desire"></Item>;
    }
}

export default App;

2.2 class I components

How to get the passed value in the child class component after passing the value to the child component through the custom attribute in the parent component?

We can obtain the value passed to the child component through this.props attribute in the child class component, as follows:

import React, { Component } from "react";

class Item extends Component {
    render() {
        return (
            <div>
                 The sea embraces all rivers, and tolerance is great,{this.props.next}.  -- {this.props.name}
            </div>
        );
    }
}

export default Item;

5, Event handling

1. Event binding

The event handling of the React element is very similar to that of the DOM element, but there is a difference in syntax. The event binding of the React element uses the method of on + event name to bind an event. Note that this is different from the native event. The native events are all lowercase, such as onClick. The events in React are humps, such as onClick. The events in React are not native events, but synthetic events.

In React, the binding events of class components and function components are similar, but this is required when binding event functions in class components, which represents a reference to the current class. There is no need to call this keyword in the function.

Function component event binding

import React from "react";

const clickHandler = () => {
    console.log("The sea embraces all rivers, and the capacity is great. Standing on a thousand feet, you are strong without desire.");
};

const App = () => {
    return <button onClick={clickHandler}>Lao Lin said</button>;
};

export default App;

Class component event binding

import React, { Component } from "react";

class App extends Component {
    render() {
        return (
            <div>
                // When using JSX syntax, you need to pass in a function as an event handler instead of a string.
                <button onClick={this.clickHandler}>Lao Lin said</button>
            </div>
        );
    }
    clickHandler() {
        console.log("The sea embraces all rivers, and the capacity is great. Standing on a thousand feet, you are strong without desire.");
    }
}

export default App;

2. Event object

In React, you can get the event object through the parameters of the event handler function. Its event object is called composite event, which is compatible with all browsers without worrying about cross browser compatibility. The methods and properties of this object are basically the same as those of the event object learned before. The difference is that the event object in React is not provided by the browser, but built internally. This event object has the same interface as the browser native event, including stopPropagation() and preventDefault(). If we want to get the native event object, we can get it through the e.nativeEvent property.

import React, { Component } from "react";

class App extends Component {
    render() {
        return (
            <div>
                <button onClick={this.clickHandler}>Lao Lin said</button>
            </div>
        );
    }
    clickHandler(e) {
        console.log("The sea embraces all rivers, and the capacity is great. Standing on a thousand feet, you are strong without desire.");
        console.log(e);
        console.log(e.nativeEvent);
    }
}

export default App;

3. Event method parameters

React has a very flexible usage for the way event methods pass parameters. Taking zhangsan as an example, the following methods are common:

  • Pass parameters through this. Event method. bind, for example:
    onClick={this.clickHandler.bind(this,'zhangsan')}
    Corresponding formal parameter receiving: clickHandler(username)

  • Use the arrow function to pass parameters, for example:
    Onclick = {() = > this. Event method ('zhangsan ')}
    Corresponding formal parameter receiving: clickHandler(username)

4. this points to the problem

This in JSX event function method will not bind this point by default. If we forget to bind, the value of this is undefined when we call this function. So be sure to bind the point of this when using!

For example, as shown in the following code, the output of this in the callback function is undefined:

import React, { Component } from "react";

class App extends Component {
    render() {
        return (
            <div>
                <button onClick={this.clickHandler}>
                    Lao Lin said
                </button>
            </div>
        );
    }
    clickHandler() {
        console.log(this);
    }
}

export default App;

There are several ways to solve the problem of this pointing above:

  • Bind through the constructor of the class component
import React, { Component } from "react";

class App extends Component {
    constructor(props) {
        super(props)
        this.clickHandler = this.clickHandler.bind(this)
    }
    
    render() {
        return (
            <div>
                <button onClick={this.clickHandler}>
                    Lao Lin said
                </button>
            </div>
        );
    }
    
    clickHandler() {
        console.log(this);
    }
}

export default App;
  • Binding with bind
import React, { Component } from "react";

class App extends Component {
    render() {
        return (
            <div>
                <button onClick={this.clickHandler.bind(this)}>
                    Lao Lin said
                </button>
            </div>
        );
    }

    clickHandler() {
        console.log(this);
    }
}

export default App;
  • Use arrow function: mode 1
import React, { Component } from "react";

class App extends Component {
    render() {
        return (
            <div>
                <button onClick={() => this.clickHandler()}>Lao Lin said</button>
            </div>
        );
    }

    clickHandler() {
        console.log(this);
    }
}
  • Use arrow function: mode 2
import React, { Component } from "react";

class App extends Component {
    render() {
        return (
            <div>
                <button onClick={this.clickHandler}>Lao Lin said</button>
            </div>
        );
    }

    clickHandler = () => {
        console.log(this);
    }
}

export default App;

6, State state

Status is the data that the component describes a certain display situation. It is set and changed by the component itself, that is, it is maintained by the component itself. The purpose of using status is to make the display of components different in different states.

state status is only available in class components, but not in function components!

1. Basic use

  • state, that is, data, is the private data inside the component and can only be used inside the component

  • The value of state is an object, indicating that there can be multiple data in a component

  • Get the status through this.state

  • The state data value can be modified to this.setState

  • state can be defined in the constructor of the class or written in the member attribute of the class

First setting method

import React, { Component } from "react";

class App extends Component {
    // Constructor initial state
    constructor(props) {
        super(props);
        this.state = {
            count: 0,
        };
    }
    render() {
        return <div>{this.state.count}</div>;
    }
}

export default App;

Second setting method

import React, { Component } from "react";

class App extends Component {
    // General initialization
    state = {
        count: 0,
    };
    render() {
        return <div>{this.state.count}</div>;
    }
}

export default App;

2. Modification status

In vue, the data property is processed by Object.defineProperty. When changing the data of data, the getter and setter of data will be triggered, but such processing is not done in react. If it is changed directly, react cannot know. Therefore, a special method to change the state, setState, needs to be used.

setState accepts two parameters. The first parameter is responsible for modifying the state itself, which we call updater; The second parameter is a callback function, because the setState method is asynchronous. If you want to do further processing after updating the state, you can use the second parameter at this time.

Syntax: this.setState(updater[,callback])

The updater parameter can be passed in two forms: object form and function form

Object form

this.setState({
    count: this.state.count + 1,
    // ....
})

Function form

this.setState(state => {
    return {
        count: state.count + 1,
    }
})

Abbreviation:

this.setState(state => ({ count: state.count + 1 }))

this.setState synchronous asynchronous

this.setState can be either asynchronous or synchronous
Operate in a react event or lifecycle. It is an asynchronous operation,
If the native js event, setTimeout/setInterval and so on, they are all synchronous operations

Asynchronous:

Tags: React

Posted on Mon, 29 Nov 2021 23:42:21 -0500 by bionicdonkey