Usage of React components

Posted by utdfederation on Thu, 10 Feb 2022 12:06:09 +0100

1. Introduction to React

React is a JAVASCRIPT library for building user interfaces.

React is mainly used to build UI. Many people think react is the V (view) in MVC.

React originated from Facebook's internal project to set up Instagram's website, and was open-source in May 2013.

React has high performance and simple code logic. More and more people have begun to pay attention to and use it.

2. How to write React

Simple example

  1. Attention to render method
    -Render multiple times, and the later rendering will overwrite the first rendering
    -The render method can render only one element / component at a time
  2. Precautions for createElement method
    -More than 3 parameters can be added, and the subsequent parameters will be processed as the content of the currently created element
  3. How to add listening to elements?
    -The essence of adding listeners to elements is to add attributes to elements
    So you can add it in the second parameter of createElement()
    -< button onclick = "btnclick" > button < / button >
    - React.createElement('button ', {onClick: btnClick},' button ');
    matters needing attention:
    If you want to bind an event to an element, the event name must be a hump name
<body>
    <div id="app"></div>
</body>
<script>
    let name = 'Lao Wang';
    let oDiv = React.createElement('div', null, name)
    let oBtn = React.createElement('button', null, 'click')
        //Click event. Both elements will be triggered
    let root = React.createElement('div', {
        onClick: fn
    }, oDiv, oBtn)
    ReactDOM.render(root, document.querySelector('#app'), () => {
        console.log('Render all');
    })
    function fn() {
        console.log('Printed');
    }
</script>

3. JSX writing method

3.1. Problems in creating elements through createElement?

-If the structure is relatively simple, it's OK, but if the structure is relatively complex, it's more difficult to start

So Daniel invented JSX, which is specially used to write the page structure in React

3.2. What is JSX?

- JSX === JavaScript + X === (XML) === (eXtension)

-JSX is a JavaScript syntax extension that looks much like XML

3.3 why use JSX?

-Using JSX makes it easier and more flexible for us to write page structure in React

-JSX is type safe and errors can be found during compilation

-JSX executes faster because it is optimized after compiling into JavaScript code

-Prevent XSS injection attacks

3.4 what is the essence of JSX?

-The browser only knows JS but not JSX, so the JSX code we write cannot be executed in the browser

-To solve this problem, we need to use babel to convert JSX into JS, that is, into react createElement();

3.5. How to convert JSX into JS in a project?

-Import Babel js

-Add type = "text/babel" to the script tag

<script src="./react17/react.development.v17.js"></script>
 <script src="./react17/react-dom.development.v17.js"></script>
 <script src="./react17/babel.min.js"></script>
<body>
    <div id="app"></div>
</body>
<script type="text/babel">
    let name = "Lao Wang";
    let myRoot = (
      <div>
        <div>{name}</div>
        <button onClick={fn}>click</button>
      </div>
    );
    ReactDOM.render(myRoot, document.querySelector("#app"), () => {
      console.log("Created successfully");
    });
    function fn() {
      console.log("output");
    }
  </script>

4. Function component

4.1. How to define components in React?

  • There are two ways to create components in React
  • The first is defined by the constructor before ES6 (stateless component)
  • The second one is defined by the class starting from ES6 (stateful component)

4.2. How to define components through the constructor of ES5

-Return the structure of the component in the constructor

<script type="text/babel">
    let name = "Lao Wang";
    function Wang() {//Create components through constructors
      return (
        <div>
          <div>{name}</div>
          <button onClick={fn}>click</button>
        </div>
      );
    }
    ReactDOM.render(<Wang />, document.querySelector("#app"), () => {
      console.log("Created successfully");
    });
    function fn() {
      console.log("Button");
    }
  </script>

5. Class component

How to define components through the class of ES6

-Define a class, implement the render method in this class, and return the structure of the component in the render method

<script type="text/babel">
    let name = "Lao Wang";
    class Wang extends React.Component {//Create components through class
      render() {
        return (
          <div>
            <div>{name}</div>
            <button onClick={fn}>click</button>
          </div>
        );
      }
    }
    ReactDOM.render(<Wang />, document.querySelector("#app"), () => {
      console.log("Created successfully");
    });
    function fn() {
      console.log("Click");
    }
  </script>

6. Difference between stateful and stateless components

6.1. Stateful components and stateless components?

-First of all, it should be clear that the state in the component actually refers to data

+Stateful components refer to components with their own data (logical components)

+Components without their own data

6.2. How to define your status?

-All inherited from react Component components inherit a state attribute from the parent class by default

This state attribute is specifically used to save the current data

-So everything is inherited from react Components of component are stateful components

-So whatever is not inherited from react The components of component are stateless components

-So class components are stateful components

-So functional components are stateless components

<script type="text/babel">
    let name = "Lao Wang";
    // function WANG(){
    //     return(
    //         <div>
    //         <div>{state + name}</div>
    //         {
    //             //state is not defined will be returned
    //         }
    //         < button onclick = {FN} > Click < / button >
    //       </div>
    //     )
    // }
    // ReactDOM.render(<WANG />, document.querySelector("#app"), () => {
    //   console.log("created successfully");
    // });
    class Wang extends React.Component {
      render() {
        return (
          <div>
            <div>{this.state + name}</div>
            {
                //The view will show null Lao Wang, which means there is a state, but now the value is null
            }
            <button onClick={fn}>click</button>
          </div>
        );
      }
    }
    ReactDOM.render(<Wang />, document.querySelector("#app"), () => {
      console.log("Created successfully");
    });
    function fn() {
      console.log("Click");
    }
  </script>

7. Usage of setState

Note about the state attribute

-Never modify state directly

-Modifying the state directly does not trigger an interface update

-The interface update is triggered only when the state is modified using the setState method

 <script type="text/babel">
    class Wang extends React.Component {
      constructor() {
        super();
        this.state = {
          name: "Lao Wang",
          age: 18, //Similar to data in vue, it is used to store static data
        };
      }
      render() {
        return (
          <div>
            <div>full name{this.state.name}</div>
            <div>Age{this.state.age}</div>
            <button onClick={()=>this.fn(this.state.age)}>click</button>
          </div>
        );
      }
      fn = (val) => {
        // this.state.age=20
        console.log('Native value',val);
        // console.log('modified value ', this. State. Age)// The state value is indeed modified, but the view will not be changed
        this.setState({
            age:21
        })
        setTimeout(()=>{//The new value can only be obtained asynchronously, because setState is usually asynchronous
            console.log(this.state.age);
        },200)
    };
    }
    ReactDOM.render(<Wang />, document.querySelector("#app"), () => {
      console.log("Created successfully");
    });
  </script>

8. this point

8.1 this pointing problem

-Before ES6, whoever called this in the method was the one who called it,

You can also modify this through the call/apply/bind method

-Starting from ES6, an arrow function has been added. The arrow function does not have its own this,

This in the arrow function is the closest this outside the function

Moreover, since the arrow function does not have its own this, it cannot be modified through the call/apply/bind method

8.2. Monitor this in the event

-When calling the listening method inside React, this of the listening method will be changed to undefined by default through the apply method

Therefore, the state of the current component cannot be obtained through this in the listening method (undefined.state)

-If you want to get the state of the current component in the listening method, you must ensure that this in the listening method is the current instance

Therefore, we can make use of the characteristics of the arrow function to make React unable to modify this in the listening method and make this in the listening method the current instance

<script type="text/babel">
    class Wang extends React.Component {
      constructor() {
        super();
        this.state = {
          name: "Lao Wang",
          age: 18, //Similar to data in vue, it is used to store static data
        };
      }
      render() {
        return (
          <div>
            <div>{this.state.name}</div>
            <button onClick={()=>{this.fn(this.state.age)}}>click</button>
          </div>
        );
      }
      fn = (val) => {
        //Equivalent to receiving an anonymous arrow function with a variable
        console.log("Click",val);
      };
    }
    ReactDOM.render(<Wang />, document.querySelector("#app"), () => {
      console.log("Created successfully");
    });
  </script>

8.3 test:

import React from 'react';
const STR = 'Called, this Point to:';
class App extends React.Component{
  constructor(){
    super()
  }
  //Test function
  handler() {
    console.log(`handler ${STR}`,this);
  }
  render(){
    console.log(`render ${STR}`,this);
    return(
      <div>
        <h1>hello World</h1>
        <label htmlFor = 'btn'>Click Print function handler in this Direction of</label>
        <input id = "btn" type="button" value = 'single click' onClick = {this.handler}/>
      </div>    
    )
  }
}
export default App

Topics: Front-end