My react learning

Keywords: Javascript React npm

Basic Section

Create a react project

  • Create a react project

    Global installation react directive

        // Install react globally (not required if required)
        npm i -g react // Or yarn-global react
    
        // Scaffold for global react installation (Scaffold must be installed to create react applications)
        npm i -g create-react-app // Or yarn-global create-react-app

    Use scaffolding to create applications

    create-react-app apply name
    // For example, create a TodoList application
    create-react-app todo-list

    Note:

      1. Install create-react-app globally to create applications using scaffolding
      2. The application name is all lowercase letters, no such name as "TodoList" can appear

Use of components

  • Components

        // React is essential to the react component and is used for modules that support jsx syntax. Although no references are visible, they are necessary
        // Component All react components inherit from Component, which is the base class of react components
        import React, { Component } from 'react';
    
        // TodoItem custom components
        import TodoItem from "./TodoItem"
    
        // Define a TodoList component that inherits from the base class Component
        class TodoList extends Component {
                /***
                 * constructor Constructor for current class
                * props Simple understanding: is a parameter passed by a parent class, such as a value or method passed, and it is an object
                * super(props) A simple understanding is to inherit parameters passed in a parent class
                **/
            constructor(props){
                super(props)
                // A state is a repository of all react variables, with the simple understanding that the variables of the current component are placed in this object
                this.state = {
                    inputValue: "",
                    List: []
                }
                // bind this so that this in the method always points to the current component (you can change this direction as needed)
                this.getList =  this.getList.bind(this)
                this.inputChang = this.inputChang.bind(this)
                this.addItem = this.addItem.bind(this)
                this.delItem = this.delItem.bind(this)
            }
            // A necessary method for the react component, return returns a jsx-like template, which you can understand as html+js-like
            render() {
                return (
                    {/*There can only be one root tag in jsx, wrapped in <></> (ghost tag), which satisfies the syntax format of jsx, does not resolve ghost tags when browser parses, and reduces the dom tree structure node */}
                    <>
                        <div>
                            <input value={this.state.inputValue} onChange={this.inputChang} /> <button onClick={this.addItem}>Add to</button>
                        </div>
                        <ul>
                            {this.getList()}
                        </ul>
                    </>
                );
            };
    
            // Traverse output item
            getList() {
                ...
            }
            // Dynamically change the value of the input box
            inputChang( e ) {
                ...
            }
    
            // Add item
            addItem() {
                ...
            }
    
            // Delete item
            delItem(index) {
                ...
            }
        }
        // Export TodoList
        export default TodoList;
  • Understanding jsx

    Simple jsx syntax

    ...
        render() {
            return (
                {/*There can only be one root tag in jsx, wrapped in <></> (ghost tag), which satisfies the syntax format of jsx, does not resolve ghost tags when browser parses, and reduces the dom tree structure node */}
                <>
                    <div>
                        <input value={this.state.inputValue} onChange={this.inputChang} /> <button onClick={this.addItem}>Add to</button>
                    </div>
                    <ul>
                        {this.getList()}
                    </ul>
                </>
            );
        };
    
    ...
    1. There can only be one root tag in jsx, wrapped in <> </> (ghost tag), which satisfies the syntax format of jsx, does not parse ghost tags in browser parsing, reduces dom tree structure nodes, and can use code snippets (Fragments). The effect is the same as <> /> except that Fragments are more widely used, which will be explained in more detail later

    2. Use comments in jsx, multiple lines use {/* comment content */}, single line use

          //Multiline
      
          {/*Multiline comment content*/}
          {/*
              Multiline comment content
          */}
      
      
          //Single line
          {
              //Single line comment content
          }
      
    3. Use component variables or methods in jsx, wrap with {}

    4. The method bound in jsx defaults this to undefined, so bind is required to bind this's direction

          // Mode 1: Specify this in the constructor
          constructor(props){
              super(props)
              this.state = {
                  inputValue: "",
                  List: []
              }
              this.getList =  this.getList.bind(this)
              this.inputChang = this.inputChang.bind(this)
              this.addItem = this.addItem.bind(this)
              this.delItem = this.delItem.bind(this)
          }
      
          // Mode 2: Specify this when binding events
      
          ...
              <li onClick={this.delItem.bind(this,index)}></li>
          ...
      
  • Basic communication of components

  1. The simplest parent--->child

    // Parent components pass data by setting properties on child component labels
        <Boy
            teacherName={ this.state.teacherName }
        />
    
        <Girl
            teacherName={ this.state.teacherName }
        />
    
    // Subcomponents get data passed by the parent component through this.props
    // this.props.teacherName gets the name of the teacher
        render(){
            return (
                <>
                    <p>
                        //I am {this.state.boyName}, and my teacher is {this.props.teacherName},
                        //I am very kind to my teacher
                        <button onClick={()=> this.props.say(this.state.boyName,"Satisfied") } >
                            //Satisfied
                        </button>
                    </p>
                </>
            )
        }
    
  2. The simplest child - > parent communication

    // Parent components pass data by setting properties on child component labels
        <Boy
            say = { this.stuSay }
        />
    
        <Girl
            say = { this.stuSay }
        />
    // Subcomponents get data passed by the parent component through this.props
    // this.props.say gets the method provided by the parent component, passes in the passed data as a parameter by calling the parent component's method, and when the parent component's method is called, gets the data passed by the child component by getting the current method parameter
        render(){
            return (
                <>
                    <p>
                        //I am {this.state.boyName},
                        //I am very kind to my teacher
                        <button onClick={()=> this.props.say(this.state.boyName,"Satisfied") } >
                            //Satisfied
                        </button>
                    </p>
                </>
            )
        }
    
  3. The simplest non-parent-child communication

Core idea: find a common parent component and use the values and methods passed by the parent component

The process is somewhat complicated, which is omitted here

teacher.js

import React,{ Component } from "react"

// Import Boy (Boy) and Girl (Girl) components
import Boy from "./boy"
import Girl from "./girl"

export default class Teacher extends Component {
    constructor(props){
        super(props)
        this.state = {
            teacherName: "Tom",
            stuName: "",
            stuSayContent: "",
            boyName: "",
            girlName: "",
            boySayContent: "",
            girlSayContent: ""
        }
        this.stuSay = this.stuSay.bind(this);
        this.boySaySecret = this.boySaySecret.bind(this);
        this.grilSaySecret = this.grilSaySecret.bind(this);
    }
    render(){
        let evaluation = false
        if (this.state.stuName!=="" && this.state.stuSayContent) {
            evaluation = true
        }
        return (
            <>
                <p>I am{ this.state.teacherName }Teacher</p>

                <div>
                    {
                        evaluation ? (<p>Student Evaluation:{this.state.stuName}Very much to me{this.state.stuSayContent}</p>) : " "
                    }
                </div>

                <Boy
                    say = { this.stuSay }
                    teacherName={ this.state.teacherName }
                    boySaySecret = {this.boySaySecret}
                    girlSayContent = {this.state.girlSayContent}
                />

                <Girl
                    say = { this.stuSay }
                    teacherName={ this.state.teacherName }
                    grilSaySecret = {this.grilSaySecret}
                    boySayContent = {this.state.boySayContent}
               />
            </>
        )
    }
    stuSay(stuName,stuSayContent){
        this.setState(()=>{
            return {
                stuSayContent,
                stuName
            }
        })
    }
    boySaySecret(constent){
        this.setState(()=>{
            return {
                boySayContent : constent
            }
        })
    }
    grilSaySecret(constent){
        this.setState(()=>{
            return {
                girlSayContent : constent
            }
        })
    }
}

boy.js

import React,{ Component } from "react"

export default class Boy extends Component {
    constructor(props){
        super(props)
        this.state = {
            boyName: "Longzhentian"
        }
    }
    render(){
        return (
            <>
                <p>
                    //I am {this.state.boyName}, and my teacher is {this.props.teacherName},
                    //I am very kind to my teacher
                    <button onClick={()=> this.props.say(this.state.boyName,"Satisfied") } >
                        //Satisfied
                    </button>,
                    //I want to say to the girl: <button onClick={()=> this.props.boySaySecret("I like you")}> Silently </button>,
                    //She said to me: {this.props.girlSayContent}

                </p>
            </>
        )
    }

}

gril.js

import React,{ Component } from "react"

export default class Boy extends Component {
    constructor(props){
        super(props)
        this.state = {
            girlName: "Pity Xiangyu"
        }
    }
    render(){
        return (
            <>
                <p>
                    //I am {this.state.girlName}, and my teacher is {this.props.teacherName},
                    //I am very kind to my teacher
                    <button onClick={()=> this.props.say(this.state.girlName,"Dissatisfied") } >
                        //Dissatisfied
                    </button>,
                    //I want to say to the boy: <button onClick={() => this.props.grilSaySecret ("Me too")}>Silently </button>,
                    //He said to me: {this.props.boySayContent}
                </p>
            </>
        )
    }

}

Advanced Section

To be continued...

Posted by dmschenk on Fri, 17 May 2019 17:17:07 -0700