Shiv ENOW large front end

Company official website: CVTE(Guangzhou Shiyuan Stock)

Team: ENOW team of CVTE software Platform Center for Future Education

The author:

I met the React

What’s the React

  1. React, Vue, and Angular are known as the front-end framework troika
  2. React grew out of an internal project at Facebook, where the company was unhappy with all the JavaScript MVC frameworks on the market and decided to write one for Instagram. After it was built, it was found to be very useful and opened source in May 2013
  3. React is a JAVASCRIPT library for building user interfaces.
  4. React is primarily used to build UIs, and a lot of people think of React as the V of MVC.

The characteristics of the React

Scaffolding – My first React project

What is scaffolding?

Scaffolding is a method of metaprogramming that allows you to quickly build code templates by typing in a single command.

  1. Global erection scaffolding
NPM install -g create-react-app // Windows sudo NPM install -g create-react-app // MAC/LinuxCopy the code
  1. Use scaffolding to create new projects
Create-react-app react-demo // react-demo is your project nameCopy the code
  1. Start the project
cd react-demo
npm run start
Copy the code
  1. Start-up success

React Prerequisites

JSX

Let’s look at the following code:

const element = <h1>Hello, world!</h1>;
Copy the code

This interesting tag syntax is neither a string nor HTML.

It’s called JSX, and it’s a syntax extension to JavaScript. We recommend using JSX with React. JSX is a good way to describe how the UI should behave as it should interact. JSX may be reminiscent of a template language, but in fact it has all the functionality of JavaScript.

How do I write the JSX expression?

  1. Ordinary rendering
<h1> I am JSX </h1>Copy the code
  1. Mathematical expression
    <h1>{1 + 1}</h1>
Copy the code
  1. string
    <h1>{'hello world'}</h1>
Copy the code
  1. Bool – Cannot render
    <h1>{isBoy}</h1>
Copy the code
  1. Use the variable
    <h1>{msg}</h1>
Copy the code
  1. Ternary operator
    <h1>{isBoy ? "Boys" : "Girls"}</h1>
Copy the code
  1. A method is called
  const format = (msg) = > {
     return The '-' + msg + The '-';
   }    

  <h1>{format(msg)}</h1>
Copy the code
  1. Using the object
   const lamian = {
     name: "Noodles"
   };

  <h1>{lamian.name}</h1>
Copy the code

JSX nested syntax and loops

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

const list = ['apple'.'banana'.'snow pear'.'watermelon'];

const App = () = > {
  return (
    <div >
      {
        <div>
          {
            list.map(v => <h1 key={v}>{v}</h1>}}</div>
      }
    </div>
  )
}

ReactDOM.render(<App />.document.getElementById('root'))
Copy the code

JSX Label attributes

JSX tags allow you to set most of the HTML tag attributes, such as checked, SRC, etc., but there are a few points to note:

  1. Change the HTML class attribute to className
     <div className="redCls"> 👍 💯 ☁ ️ < / div >Copy the code
  1. Change the for attribute of the LABEL tag in HTML to htmlFor
  <label htmlFor="inp"<input id="inp" type="text" />
  </label>
Copy the code
  1. The custom attributes in the tag use data
  <div data-index={'hello'} > Custom attribute </div>Copy the code
  1. Render THE HTML string using the dangerouslySetInnerHTML attribute
  <li dangerouslySetInnerHTML={{__html:< I > come on 
      }}></li>
Copy the code
  1. A value of type bool can be used this way
  <input type="checkbox" checked={true} / >Copy the code
  1. When there are too many attributes, use… Extended operator
  const props={
   className:"redCls"."data-index":5} <div {... Props}> Expand property </div>Copy the code
  1. Inline style
  <div style={{ color: 'yellow'.fontSize: "150px"."backgroundColor": 'red'}} > </div>Copy the code

For styled JSX, highlight JSX code and improve the programming experience.

Component creation

In React, there are two types of components, class components and functional components

  1. Simple functions use functional components
  2. Complex functions use class components
  3. Component names must be capitalized

Class components

Implement a component Class the way ES6 creates classes

  • Capitalize the first letter
  • To inheritReactIn theComponentclass
  • Must be implementedrenderFunction, which returns a label
  • Components have their ownstateAnd the life cycle
import React,{Component} from 'react';
import ReactDOM from 'react-dom';
import "./index.css";

 class App extends Component {
  render() {
    return (
      <div>Gnome male -"</div>
    )
  }
}
ReactDOM.render(<App />.document.getElementById('root'))
Copy the code

Functional component

Also called stateless components, components with simple functions can use functional components for higher performance.

A functional component is a function that returns the corresponding label

  • Capitalize the first letter
  • The label is returned inside the function
import React from 'react';
import ReactDOM from 'react-dom';
import "./index.css";

const App = () = > {
  return (
    <div>Simple functional components</div>
  )
}

ReactDOM.render(<App />.document.getElementById('root'))
Copy the code

summary

  • Functional components perform better because they have no life cycle
  • Functional components are easier to test
  • Don’t use class components if you can
  • When using state, use class components

States and Properties

React uses state and properties to animate data. Let’s talk about these two concepts separately.

State: the state

How to understand state?
  • In the react,Components,The data is passedstateTo implement and manage
  • Can be understood asstateisVueIn thedata
Why do WE need state?

We’ve been using variables in isolation from the component itself. The component itself should have private and independent data (state), this private data and state is called state, in the future, as long as the state of the data refers to the state in the class component

⚠️ : Functional components do not have their own state

Declaration and use of state (two ways)
  1. A method declaration for a class attribute
 class Person extends Component {
  // 1 declare state
  state = {
    date: "2021".msg: "Hello"
  }
  render() {
    return (
      <div>{/* 2 state */}<h1>{this.state.date}</h1>
        <h2>{this.state.msg}</h2>
      </div>)}}Copy the code
  1. Constructor
 class Person extends Component {
  // declare state in the 1 constructor
  constructor() {
    // 1.1 must call the super() method before this
    super(a);this.state = {
      date: "2009".msg: "Oh, my God. Oh, my god."}}render() {
    return (
      <div>{/* 2 state */}<h1>{this.state.date}</h1>
        <h2>{this.state.msg}</h2>
      </div>)}}Copy the code
Assignment of state (note the distinction between assignment and declaration)
  • stateCan only be assigned bythis.setStateMethod to implement.

Date = 200; this.state.date= 200;

  • The assignment of state is asynchronous.

React changes the state assignment code to asynchronous to optimize performance. This avoids performance loss caused by repeated state Settings.

How? Take a look at the values printed below

 class Person extends Component {
  state = {
    date: 2010
  }
  handleClick = () = > {
    let { date } = this.state;

    // 1 Change the date in state to add 2000
    this.setState({
      date: date + 2000
    });

    // 2 Let's see what the date is
    console.log(this.state.date);
  }
  render() {
    return (
      <div onClick={this.handleClick}>
        <h1>{this.state.date}</h1>
      </div>)}}Copy the code

Sometimes we want to get the latest state value as soon as we set the value, so we can rewrite the code as follows

Add a callback function to setState that retrieves the value of the latest state

 class Person extends Component {
  state = {
    date: 2008
  }

  handleClick = () = > {
    let { date } = this.state;

    // Add a callback function
    this.setState({
      date: date + 3000
    }, () = > {
      // date的值为 3008
      console.log(this.state.date);
    });
  }
  render() {
    return (
      <div onClick={this.handleClick}>
        <h1>{this.state.date}</h1>
      </div>)}}Copy the code

Sometimes, setState can also receive a function that retrieves the value of state in real time, without delay

    this.setState(preState= > {
      console.log("Last state", preState.date);
      return {
        date: preState.date + 1000}})this.setState(preState= > {
      console.log("Last state", preState.date);
      return {
        date: preState.date + 1}})Copy the code

Properties props

Props stands for properties and generally exists in parent components. It is used to pass data from parent to child.

Let’s demonstrate this in code

  1. Declare the parent component and pass data as properties on the tag
   import HomeTop from Relative path		// Introduce child components
   import HomeFooter from Relative path
   
   class Home extends Component {
     state = {
       color: "blue".size: 100
     }
     render() {
       return (
         <div>
           <HomeTop acolor={this.state.color} asize={this.state.size} ></HomeTop>
           <HomeFooter bcolor={this.state.color} bsize={this.state.size}  ></HomeFooter>
         </div>)}}Copy the code

Note that the variable names in the parent component are color and size, while the variable names in HomeTop and HomeFooter are acolor asize and bcolor bsize, respectively.

  1. Declare a class component, HomeTop, throughthis.propsTo get the parent component’s data
   class HomeTop extends Component {
     render() {
       return (
         <h1>The color of the roof is {this.props. Acolor} size {this.props. Asize}</h1>)}}Copy the code
  1. Declare a functional componentHomeFooterThe parent component passes the data needed in the function’s parameterspropsOn receiving
   const HomeFooter = (props) = > {
     return <h1>The color of the bottom of the house is {props. Bcolor} size {props. Bsize}</h1>
   }
Copy the code

Write in the last

There is a lot to learn if you want to learn react development, including, but not limited to, the React lifecycle, hooks, and redux, which are shared here due to space constraints. I hope this article can help you a little bit.