Installation and use of React scaffold and basic syntax of React

1. React installation

1.1. Use React scaffold for installation

1.cnpm install -g create-react-app

2. Replace the source npm config set registry https://registry.npm.taobao.org

npm config set registry https://registry.npm.taobao.org
-- After configuration, you can verify whether it is successful by the following methods
npm config get registry
-- If the above address is displayed, the replacement is successful

3. Create todolist create react app todolist

4. Enter the cd todolist directory

5. Start project npm start

1.2 simplification of scaffold code

Description of project directory:

node_ Modules = = > related dependencies of NPM Download
package. JSON = = = > the node package file includes some descriptions of the project and related file versions

public folder:

​ index. HTML = = > the first page of the project

​ favico. ICO = = > item icon

​ mainfest. JSON = = > define web page shortcuts

src folder:

​ index. JS = = > entry file of the whole project
​ registerServiceWorker. JS = = > offline cache

Code engineering simplification

Save only app. In src directory JS and index JS file

index.js is the entry file. The simplified code is as follows:

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

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

App. The simplified code of JS file is as follows:

import React from 'react';

function App() {
  return (
    <div>
      hello React...
    </div>
  );
}

export default App;

2. React basic syntax

2.1. JSX syntax Basics

React uses JSX instead of regular JavaScript.

JSX is a JavaScript syntax extension according to the XML syntax specification.

JSX 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;
  • Writing templates using JSX is easier and faster.

**Essence of JSX syntax: * * instead of directly rendering JSX to the page, it is internally converted to the form of createElement and then rendered.

**JSX comment: * * it is recommended to use {/ * this is the comment * /};

**Add class name to JSX: * * you need to use className instead of class; htmlFor replaces the for attribute of label;

When JSX creates DOM, all nodes must have unique root elements to wrap;

In JSX syntax, tags must appear in pairs. If they are single tags, they must be self closing and self closing;

Code example:

const mydiv = <div>This is a Div label</div>;
ReactDOM.render(mydiv, document.getElementById('root'));

Examples of developing code using componentization:

App.js component file code

import React from 'react';

class App extends React.Component{
  render(){
    return (
      <div>
        {1+1}
        <hr/>
        Hello,Reactjs!!
      </div>
    );
  }
}

export default App;

Use JSX syntax to reference components in other files:

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

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

Render digital

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

let a = 10;

ReactDOM.render(
    <div>{a}</div>
, document.getElementById('root'));

Render string

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

let str = 'hello react';

ReactDOM.render(
    <div>{str}</div>
, document.getElementById('root'));

Render boolean type

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

let rel = true;

ReactDOM.render(
    <div>{rel ? 'The result is true' : 'The result is false'}</div>
, document.getElementById('root'));

Render attribute values

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

let title = "this is a div";

ReactDOM.render(
    <div title={title}>Hello React</div>
, document.getElementById('root'));

Render label objects

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

const h1 = <h1>Hello React!</h1>;

ReactDOM.render(
    <div>
        {h1}
    </div>
, document.getElementById('root'));

Render array

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

const arr = [
    <h1>Line 1</h1>,
    <h2>Line 2</h2>,
];

ReactDOM.render(
    <div>
        {arr}
    </div>
, document.getElementById('root'));

Convert the normal array to JSX array and render it to the page

Solving Warning: Each child in a list should have a unique "key" prop

Method 1:

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

//Original array
const arr = ['html','css','vue'];
//New array
const newArr = [];
//The forEach() method has no return value
arr.forEach((item,index) => {
    const temp = <h2 key={index}>{item}</h2>
    newArr.push(temp);
});

ReactDOM.render(
    <div>
        {newArr}
    </div>
, document.getElementById('root'));

Method 2:

import React from 'react';
import ReactDOM from 'react-dom';
import TodoList from './TodoList';
import './style.css';

//Original array
const arr = ['html','css','vue'];

ReactDOM.render(
    <div>
    	{/* map()Method has a return value */}
        {arr.map((item,index) => {
        return <h2 key={index}>{item}</h2>
        })}
    </div>
, document.getElementById('root'));

2.2. React component

Component concept

React applications are built on components.

As the core content of React, component is an important part of View. Each View page is composed of one or more components. It can be said that component is the cornerstone of React application. In the component composition of React, it can be divided into stateful components and stateless components according to the state.

Characteristics of components

The concept of componentization has existed in the back end for many years, but in recent years, with the development of the front end, this concept has been frequently mentioned in the front end, especially in the framework of MV *.

The word "componentization" in the front end usually refers to "tagging" in the UI layer, that is, dividing a large business interface into several small pieces and then assembling them.

In a narrow sense, componentization is generally indicator signing, that is, a mechanism with user-defined tags (user-defined attributes) as the core.

In a broad sense, componentization includes combing the business of data logic layer to form capability encapsulation at different levels.

  • Standardization

    Any component should comply with a set of standards, which can enable developers in different regions to develop a set of standardized components.

  • Combination

    Components should be composable before. We know that the display of front-end pages is a combination of HTML and DOM, and the final form of components can also be understood as HTML fragments. Therefore, the composition of a complete interface display must depend on the combination, nesting and communication between different components.

  • reusability

    Any component should be an independent individual that can be applied in different scenarios.

  • Maintainability

    Any component should have its own complete and stable functions, including only its own logic independent of other components, so as to make it easier to understand and understand, and greatly reduce the probability of bug s.

Function component

The stateless functional component is formally represented as a component class with only one render() method, which is created in the form of function or ES6 arrow function, and the component is stateless. The specific creation form is as follows

import React from 'react';

//Define a React component
function App() {
  return (
    <div>
      hello React...
    </div>
  );
}

export default App;

class component

React.Component creates react components in the form of ES6, which is a highly recommended way to create stateful components. The form is changed to react The form of component is as follows

import React from 'react';

//Define a React component
class App extends React.Component{
  render(){
    return (
      <div>
        Hello,Reactjs!!
      </div>
    );
  }
}

export default App;

Reference components in other files

import React from 'react';
import ReactDOM from 'react-dom';
//App component, the component must start with a capital letter
import App from './App';

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

Difference between function component and class component

The component created by constructor is called "stateless component";

The component created with the class keyword is called "stateful component";

The essential difference between stateful and stateless components is whether there is a state attribute.

be careful:

Components created with the class keyword have their own private data (this.state) and life cycle functions;

The components created with function only have props, and do not have their own private data and life cycle functions;

Of course, there are differences between function components and class components, and the performance of function components is higher than that of class components, because class components need to be instantiated when used, and function components can directly execute functions to get the returned results. To improve performance, try to use function components

differenceFunction componentclass component
Is there thisNo,have
Is there a life cycleNo,have
Is there a stateNo,have

Keywords: Javascript React

Added by B.Murali Krishna on Fri, 14 Jan 2022 01:06:46 +0200