Basic tutorial for getting started with React

Posted by riddlejk on Sat, 01 Jan 2022 09:05:17 +0100

Basic tutorial for getting started with React

What is React?

React is a declarative, efficient and flexible JavaScript library for building user interfaces. Using react, you can combine some short and independent code fragments into a complex UI interface. These code fragments are called "components"

What are the characteristics of React?

  1. Virtual Dom node
  2. Unidirectional data flow
  3. Component development thinking

Grammatical features of React

	jsx: javascript and xml (htm1)Mixed label writing

effect:

  1. Writing html templates in javascript
  2. There is and only one root node
  3. class should be written as className
  4. You can write JavaScript in {}
  5. html tags can be written directly in the array
  6. For comments, {/ * * /}

Installation of React

//Install globally
npm i -g create-react-app
//Create project myreact is the name of the project you created
create-react-app myreact

cd into your project

cd myreact

Open the project using npm start

npm start

When this page appears, it indicates that the page has been created successfully

Considerations for React

The import method is generally used to introduce React. The initial of React is larger, because jsx will use uppercase React by default

  • It will be judged as html according to angle brackets (<) and js according to curly brackets ({)
  • The reserved word keyword in js will be converted
  • Class = > classname for = > adjacent jsx elements of htmlfor react,
  • The react element must be wrapped by a label < > < / >
  • The style tag must be an object style = {}} / {} indicates that {} in js indicates that an object annotation needs to be wrapped with {}
  • Dangerously setinnerhtml is dangerous. Parse html and stuff content into elements in the way of innerHtml

React template syntax

1. Conditional rendering

(1) Ternary operator
If isLog is true, "welcome back" and "braised pork" are displayed. If it is false, "please log in" is displayed

 {this.state.isLog?<p>welcome back</p>:<p>Please login</p>}
 {this.state.isLog&&<p>braised pork in brown sauce</p>}

2. List rendering

import React, { Component } from 'react'

export default class App extends Component {
  constructor(props){
    super(props)
    this.state={
      list:['vue','react','jquery','js'],
    }
    render() {
	    return (
	      <div>
	          {this.state.list.map(item=><p key={item}>{item}</p>)}
	      </div>
	    )
	  }
  }

The browser rendering result is:

3. Text rendering

{2+3}
//Browser render results: 5
//It can also be written as:
export default class App extends Component {
  constructor(props){
    super(props)
    this.state={
     msg:"Hello react",
    }
    render() {
	    return (
	      <div>
	          {this.state.msg}
	      </div>
	    )
	  }
  }

3. Events

Consistent with ordinary js events, hump writing is required

onClick={this.sayHi}
onClick={()=>{this.sayHi(parameter)
onClick={this.sayHi.bind(this,parameter)

Example:

export default class App extends Component {
sayHi=(msg="china")=>{
    alert(msg)
  }
render() {
    return (
	      <div>
	      	//Three different ways of writing
	          <button onClick={()=>alert('happy new year')}>to greet</button>
	          <button onClick={()=>{this.sayHi('china')}}>Transmission parameter</button>
	          <button onClick={this.sayHi.bind(this,'The Chinese don't lie to the Chinese')}>Pass parameter 2</button>
	      </div>
     )
   }
  }

4. Update status setState

  • It is provided by the parent class and used to modify the status. This way of updating the status will not overwrite the previous, but will only compare and merge the updated status
  • this.setState will refresh the page if you don't use this setState. Whether directly modifying state will change the state or the page will not refresh
  • If you need to change the attribute, you can only change the attribute (props) to state
this.setState({k:v})
this.setState({k:v},()=>{console.log"Callback function after execution")}
onClick={()=>{this.setState({isLog:!this.state.isLog},()=>{console.log('Switching complete');})}}

Code example:

export default class App extends Component {
constructor(props){
    super(props)
    this.state={
      isLog:false,
    }
  }
render() {
    return (
	      <div>
	         <button onClick={()=>{
            	this.setState({isLog:!this.state.isLog},()=>{
              console.log('Switching complete');
            })
          }}>switch</button>
	      </div>
     )
   }
  }

Components of React

Function component

 function App{
   return(
     <div></div>
 )
} 
 export default App

Insufficient of title function component

  • No status, new version added
  • The new version of hooks without life cycle has been added
  • There is no this in the function component

Class component

  • Class components call the render method by default when rendering
  • Class components have state and hook functions
  • Need to inherit react Component
  • React.Component is a base class with a life cycle and methods to change state
  • Inherit React Component is a React class.
 import React, { Component } from 'react'
 export default class App2 extends Component {
   render() {
     return (
       <div></div>
     )
   }
 }

Data source of React (props (external incoming, non modifiable), state (internal, modifiable))

  • Props will put the attribute or method passed in by the component on this -- when taking value: this props. name
  • this.state - value: this state. name

Developer Tools

Installing the extended React Devtools in Chrome or Firefox allows you to view the React component tree in the browser developer tool.


You can also check the state and props of the React component in React DevTools.
After installing React DevTools, right-click any element of the page and select "view", so that the developer tool of the browser can be opened, and an additional React tab (including“ ⚛️ Components and“ ⚛️ Profiler”). You can use“ ⚛️ "Components" to check the component tree.

Topics: Javascript Front-end React