Web Study Notes-React

The contents of the notes are reproduced from AcWing's web application class handouts, course link: AcWing Web Application Class .

1. React configuration environment

React official website: React .

React is a declarative, efficient and flexible JavaScript library for building user interfaces. Using React, some short, independent code fragments can be combined into complex UI interfaces, and these code fragments are called React components. React enables building large applications where data changes over time.

React features:

  • In order to maintain our pages conveniently, React creates a virtual DOM tree in memory: Virtual DOM, this is a lightweight virtual DOM, which is an object abstracted by React, describing what the DOM should look like, How it should be presented. Use this Virtual DOMto update the real DOM, and this Virtual DOMwill manage the update of the real DOM.
  • Data-driven: When the data in a certain element changes, React will re-modify all the elements that may be modified, and then compare it with the real DOM tree to see if there is any difference. After the analysis, React will only modify the result of the real change point. Because modifying objects in memory is very fast, React is very efficient.
  • React generally does not write JS directly by hand, but by writing JSX files. JSX is better to write than JS. React will first compile JSX into JS.

(1) Installation Git Bash: Windows installation Git tutorial (2022.11.18 Git2.38.1) .

(2) Installation NodeJS: Installation and configuration of NodeJS .

(3) Installation create-react-app:
Open Git bash, execute the following command:

npm i -g create-react-app

If the speed is very slow, you can modify the mirror source first and then try to install:

npm config set registry https://registry.npm.taobao.org
npm i -g create-react-app

If a warning appears after the installation is complete: npm WARN deprecated [email protected]: This version of tar is no longer supported, and will not receive security updates. Please upgrade asap., you can try updating first tar:

npm install -g tar

If there is still a warning, and an error is reported when creating the project (for example, execution create-react-app react-app): bash: create-react-app: command not found, use to npxcreate the project:

npx create-react-app my-app

Or npmcreate a project with:

npm init react-app my-app

After creation, enter the project folder to start the project:

cd my-app
npm start

The effect after startup is as follows ( ctrl+cyou can stop the service):

insert image description here

insert image description here

(4) Configure VS Code plug-ins: Simple React Snippets, Prettier - Code formatter
Simple React Snippetsare React intelligent auto-completion plug-ins:

insert image description here

For example, enter imrcthe following content to complete:

import React, {
    
     Component } from 'react';

Enter ccto complete the following:

class Example extends Component {
    
    
    state = {
    
      } 
    render() {
    
     
        return ();
    }
}
 
export default Example;

Prettier - Code formatteris the code formatting plugin:

insert image description here

(5) Create React App:
Right-click in the target directory to open Git Bash:

insert image description here

Execute in terminal:

npx create-react-app react-app  # react-app是新建项目的名字,可以替换为其他名称
cd react-app
npm start  # 启动应用

After the startup is successful, a 3000 port will be opened locally, and the page effect has been shown above. Now use VS Code to open react-appthe folder:

insert image description here

Among them, node_modulesit is used to maintain various JS libraries, and all dependencies installed in the future will be placed in this folder; the one publicin it index.htmlis the page we will render in the future, and there is only one in this file <div id="root"></div>; the code srcin it index.jsis as follows:

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';

const root = ReactDOM.createRoot(document.getElementById('root'));  // 获取div同时创建为一个React对象
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

which Appis defined in App.js:

import logo from './logo.svg';
import './App.css';

function App() {
    
    
  return (
    <div className="App">
      <header className="App-header">
        <img src={
    
    logo} className="App-logo" alt="logo" />
        <p>
          Edit <code>src/App.js</code> and save to reload.
        </p>
        <a
          className="App-link"
          href="https://reactjs.org"
          target="_blank"
          rel="noopener noreferrer"
        >
          Learn React
        </a>
      </header>
    </div>
  );
}

export default App;

This Appcomponent defines the specific content of the page, and we can find that there is HTML code in the JS file, so this file is a JSX file, which can support XML (Extensible Markup Language) on the basis of JavaScript, and HTML is also a special XML.

JSX is a language in React that is compiled into standard JavaScript by Babel .

2. ES6 grammar supplement

ES6, the full name of ECMAScript 6.0, is the version standard of JavaScript. Add some syntactic sugar commonly used in React here.

(1) Use bind()function binding to get thisvalue
In JavaScript, the function thispoints to the caller at the time of execution, not the object at the time of definition. For example:

const person = {
    
    
  name: "abc",
  talk: function() {
    
    
    console.log(this);
  }
}

person.talk();

const talk = person.talk;
talk();

The result of the operation is:

{name: 'abc', talk: f}
undefined

Use the value bind()bound by the function . For example:thisperson

const talk = person.talk.bind(person);

The result of the operation is:

{name: 'abc', talk: f}
{name: 'abc', talk: f}

(2) Shorthand way of arrow function
When the function parameter has only one, the parentheses can be removed, and when the function body has only one returnstatement, returnthe and can {}be removed together, for example:

const f = (x) => {
    
    
  return x * x;
};

Equivalent to:

const f = x => x * x;

(3) The arrow function does not rebind thisthe value

const person = {
    
    
  talk: function() {
    
    
    setTimeout(function() {
    
    
      console.log(this);
    }, 1000);
  }
};

person.talk();  // 输出Window
const person = {
    
    
  talk: function() {
    
    
    setTimeout(() => {
    
    
      console.log(this);
    }, 1000);
  }
};

person.talk();  // 输出 {talk: f}

(4) Deconstruction of objects

const person = {
    
    
  name: "abc",
  age: 18,
  height: 180,
};

const {
    
    name : new_name, age} = person;  // new_name是name的别名

(5) Expansion of arrays and objects

let a = [1, 2, 3];
let b = [...a];  // b是a的复制,和a不是一个数组,如果写let b = a则b和a是同一个数组
let c = [...a, 4, 5, 6];  // c = [1, 2, 3, 4, 5, 6]

let d = {
    
    name: "abc"};
let e = {
    
    age: 18, height: 180};
let f = {
    
    ...d, ...e, weight: 120};  // f = {name: "abc", age: 18, height: 180, weight: 120}

(6)Named exports与Default exports

  • Named Export: It can be exportmore than one. importWhen using braces, the name needs to match, that is, the method used before.
  • Default Export: At most exportone, importyou don’t need braces, you can directly define an alias.

3. Components

(1) Create a project
First create a new project box-app:

npx create-react-app box-app
cd box-app
npm start

Install bootstrapthe library:

npm i bootstrap

bootstrapThe import method:

import 'bootstrap/dist/css/bootstrap.css';

(2) Create Component
Create a folder in srcthe folder componentsto store components, and then componentscreate a JSX file in the folder ( the same is true box.jsxfor using suffixes, but it is more obvious after use). The framework is as follows:.js.jsx

import React, {
    
     Component } from 'react';  // 输入imrc即可补全

class Box extends Component {
    
      // 输入cc即可补全
    state = {
    
      } 
    render() {
    
      // Component类的函数,用来返回当前组件最后渲染的HTML结构是什么
        return (<h1>Hello World!</h1>);
    }
}
 
export default Box;

Then we need to index.jsrender the component in:

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import 'bootstrap/dist/css/bootstrap.css';
import Box from './components/box';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <Box />
  </React.StrictMode>
);

(3) Create a button Since the function
in Component can only have one element, when the number of child nodes is greater than 1, you can use or enclose it.render()return<div><React.Fragment>

(4) Embedded expressions
JSX uses {}embedded expressions in HTML tags.

(5) Setting attributes
Since classit is a keyword in JS, it classneeds to be changed in the HTML tag className. CSS properties also need to be modified, for example: background-colormodified to backgroundColor, other properties are similar.

Comprehensive example:

import React, {
    
     Component } from 'react';  // 输入imrc即可补全

class Box extends Component {
    
      // 输入cc即可补全
    state = {
    
     
        x: 0
    };

    styles = {
    
    
        width: '50px',
        height: '50px',
        backgroundColor: 'lightblue',
        color: 'white',
        textAlign: 'center',
        lineHeight: '50px',
        borderRadius: '5px'
    };

    render() {
    
      // Component类的函数,用来返回当前组件最后渲染的HTML结构是什么
        return (
        // HTML标签中可以使用{}写一个表达式
        <React.Fragment>
            <div style={
    
    this.styles}>{
    
    this.state.x}</div>
            <button className='btn btn-primary m-2'>Left</button>
            <button className='btn btn-success m-2'>Right</button>
        </React.Fragment>
        );
    }
}
 
export default Box;

(6) Data-driven change of Style,
for example:

import React, {
    
     Component } from 'react';  // 输入imrc即可补全

class Box extends Component {
    
      // 输入cc即可补全
    state = {
    
     
        x: 1
    };

    render() {
    
      // Component类的函数,用来返回当前组件最后渲染的HTML结构是什么
        return (
        // HTML标签中可以使用{}写一个表达式
        <React.Fragment>
            <div style={
    
    this.getStyles()}>{
    
    this.state.x}</div>
            <button className='btn btn-primary m-2'>Left</button>
            <button className='btn btn-success m-2'>Right</button>
        </React.Fragment>
        );
    }

    getStyles() {
    
    
        let styles = {
    
    
            width: '50px',
            height: '50px',
            backgroundColor: 'lightblue',
            color: 'white',
            textAlign: 'center',
            lineHeight: '50px',
            borderRadius: '5px'
        };

        if (this.state.x === 0) {
    
    
            styles.backgroundColor = 'orange';
        }

        return styles;
    }
}
 
export default Box;

(7) Rendering list
Functions can be used to maprender a list, and each element needs to have a unique keyattribute to help React quickly find the modified DOM element, for example:

import React, {
    
     Component } from 'react';  // 输入imrc即可补全

class Box extends Component {
    
      // 输入cc即可补全
    state = {
    
     
        x: 1,
        colors: ['red', 'green', 'blue']
    };

    render() {
    
      // Component类的函数,用来返回当前组件最后渲染的HTML结构是什么
        return (
        // HTML标签中可以使用{}写一个表达式
        <React.Fragment>
            <div>{
    
    this.state.x}</div>
            <button className='btn btn-primary m-2'>Left</button>
            <button className='btn btn-success m-2'>Right</button>
            {
    
    this.state.colors.map(color => (
                <div key={
    
    color}>{
    
    color}</div>
            ))}
        </React.Fragment>
        );
    }
}
 
export default Box;

(8) Conditional Rendering
uses the short-circuit principle of logical expressions:

  • In the same expression expr1 && expr2, the value expr1returned when false expr1, otherwise expr2the value returned.
  • or expression expr1 || expr2, the value expr1returned when true expr1, otherwise expr2the value returned.

(9) Binding events
For example, you can use onClickthe click event of the binding button. Note that the binding event function needs to be properly handled this. The example is as follows:

import React, {
    
     Component } from 'react';  // 输入imrc即可补全

class Box extends Component {
    
      // 输入cc即可补全
    state = {
    
     
        x: 1
    };

    handleClickLeft() {
    
      // 如果不用箭头函数或者下面调用函数时使用bind(this)的话this会变成undefined
        console.log('click left', this);
    }

    handleClickRight = () => {
    
    
        console.log('click right', this);
    }

    render() {
    
      // Component类的函数,用来返回当前组件最后渲染的HTML结构是什么
        return (
        // HTML标签中可以使用{}写一个表达式
        <React.Fragment>
            <div>{
    
    this.state.x}</div>
            <button onClick={
    
    this.handleClickLeft} className='btn btn-primary m-2'>Left</button>
            <button onClick={
    
    this.handleClickRight} className='btn btn-success m-2'>Right</button>
        </React.Fragment>
        );
    }
}
 
export default Box;


(10) A function is required to modify the statethis.setState() . After each this.setState()function is called, the function will be called again this.render()to modify the virtual DOM tree. React will only modify the actual DOM tree nodes out of sync. For example:

import React, {
    
     Component } from 'react';  // 输入imrc即可补全

class Box extends Component {
    
      // 输入cc即可补全
    state = {
    
     
        x: 1
    };

    handleClickLeft = () => {
    
    
        // this.state.x--;  这样写的话React不会修改前端页面的效果
        this.setState({
    
    
            x: this.state.x - 1
        });
    }

    handleClickRight = () => {
    
    
        this.setState({
    
    
            x: this.state.x + 1
        });
    }

    render() {
    
      // Component类的函数,用来返回当前组件最后渲染的HTML结构是什么
        return (
        // HTML标签中可以使用{}写一个表达式
        <React.Fragment>
            <div style={
    
    this.getStyles()}>{
    
    this.state.x}</div>
            <button onClick={
    
    this.handleClickLeft} className='btn btn-primary m-2'>Left</button>
            <button onClick={
    
    this.handleClickRight} className='btn btn-success m-2'>Right</button>
        </React.Fragment>
        );
    }

    getStyles() {
    
    
        let styles = {
    
    
            width: '50px',
            height: '50px',
            backgroundColor: 'lightblue',
            color: 'white',
            textAlign: 'center',
            lineHeight: '50px',
            borderRadius: '5px',
            position: 'relative',
            left: this.state.x
        };

        if (this.state.x === 0) {
    
    
            styles.backgroundColor = 'orange';
        }

        return styles;
    }
}
 
export default Box;

(11) To add parameters to the event function,
you can define a temporary function binding event, and then call the original function in the function and pass in the parameters, or directly use a temporary arrow function to return the original parameter when binding the event. function. For example:

import React, {
    
     Component } from 'react';  // 输入imrc即可补全

class Box extends Component {
    
      // 输入cc即可补全
    state = {
    
     
        x: 1
    };

    handleClickLeft = (step) => {
    
    
        this.setState({
    
    
            x: this.state.x - step
        });
    }

    handleClickRight = (step) => {
    
    
        this.setState({
    
    
            x: this.state.x + step
        });
    }

    handleClickLeftTmp = () => {
    
    
        this.handleClickLeft(10);
    }

    render() {
    
      // Component类的函数,用来返回当前组件最后渲染的HTML结构是什么
        return (
        // HTML标签中可以使用{}写一个表达式
        <React.Fragment>
            <div style={
    
    this.getStyles()}>{
    
    this.state.x}</div>
            <button onClick={
    
    this.handleClickLeftTmp} className='btn btn-primary m-2'>Left</button>
            <button onClick={
    
    () => this.handleClickRight(10)} className='btn btn-success m-2'>Right</button>
        </React.Fragment>
        );
    }

    getStyles() {
    
    
        let styles = {
    
    
            width: '50px',
            height: '50px',
            backgroundColor: 'lightblue',
            color: 'white',
            textAlign: 'center',
            lineHeight: '50px',
            borderRadius: '5px',
            position: 'relative',
            left: this.state.x
        };

        if (this.state.x === 0) {
    
    
            styles.backgroundColor = 'orange';
        }

        return styles;
    }
}
 
export default Box;

Guess you like

Origin blog.csdn.net/m0_51755720/article/details/127922719
Recommended