react from scratch

Keywords: React

1, react component brief introduction

Component classification:

  • Basic components: basic tags such as input and button, as well as general UI components encapsulated by antd

  • Business component: business abstraction UI composed of basic components. For example, the drop-down box of company department information

  • Block component: a UI block composed of basic components and business components

  • Page component: the final page displayed to the user, which generally corresponds to a routing rule

Specific components can be used in this blog: React learning: components_ If water is small - CSDN blog

2, Two ways to create react components

  • Create components using functions in JS
  • Create components using class in JS

Specific code examples are as follows:

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

const title = <h1>react Two components of</h1>

// Define a functional component
const Com1 = () => {
  return <div>First functional component</div>
}

// Define a class component
class Com2 extends React.Component {
  render () {
    return <div>First class component</div>
  }
}

const content = (
  <div>
    {title}
    {<Com1 />}
    <hr />
    {<Com2 />}
  </div>
)

ReactDOM.render(content, document.getElementById('root'))

Through the above code, we can compare that class components are cumbersome and functional components are simple. Let's learn about the creation of functional and class components respectively

Functional component - use functions to create components

Before using, let's first understand what function components are:   Components created using JS functions (or arrow functions)

Precautions for using function components:

  • Convention 1: capitalize the first character of function name

    It must start with a capital letter * *, according to which React distinguishes components from ordinary HTML

  • Convention 2: there must be a return value

    Represents the UI structure of the component; nul if nothing needs to be rendered

Code list:

import reactDom from 'react-dom'

// Functional component
const Hello = () => {
    return <h1>Hello</h1>
}
const app = (
    <div>
        APP
        <Hello />
    </div>)
reactDom.render(app, document.getElementById('root'))

  Class component - create a component with class

definition:   A component created using the class of ES6 is called a class component

Notes and requirements for using class components:

  • Class names must begin with an uppercase letter

  • Extensions is a keyword used to implement inheritance between classes. Class components should inherit the React.Component parent class to use the methods or properties provided in the parent class.

  • A class component must provide a render method, which must have a return value indicating the UI structure of the component. Render executes once when the component is created

Listed Code:

import reactDom from 'react-dom'
import React from 'react'


//Class component
class Hello extends React.Component {
    render () {
        return <h1>Hello</h1>
    }
}
const app = (
    <div>
        APP
        <Hello />
    </div>
)

reactDom.render(app, document.getElementById('root'))

The above two components are used in the same way  , Both single and double labels can be used

3, Stateful and stateless components

Before learning about state components, let's first understand what state is

State is the data used to describe the shape of things at a certain time, which is generally called state

Features and functions:

  • The state can be changed, and the view will change accordingly
  • Save data
  • Lay the foundation for subsequent view updates

Stateful component: a component that can define state. Class components are stateful components.

Stateless component: a component of state cannot be defined. Function components are also called stateless components (React Hooks is introduced after rect16.8, and function components can also define their own states)

After understanding the state component, let's learn about defining state and rendering transition in class component

Let's look at a code:

import reactDom from 'react-dom'
import React from 'react'
class Hello extends React.Component {
    // The state here is the state
    state = {
        list: [{ id: 1, name: 'Tomorrow will be better' }],
        isLoading: true
      };

    render () {
      return <ul>
            {this.state.list.map(item => <li key={item.id}>{item.name}</li>)}
        </ul>
    }
}
const app = (
    <div>
        <Hello />
    </div>
)

reactDom.render(app, document.getElementById('root'))

The above code is a basic use of defining state and rendering state in class components

Event binding

When we render a basic page, we need event binding to make the page have a basic interaction effect

Event binding format:

 <Element event name 1={ Event handler 1 } Event name 2={ Event handler 2 }  ></element>

// The event name adopts hump naming method: columns such as -- onMouseEnter, onFocus, onClick

Listed Code:

import reactDom from 'react-dom'
import React from 'react'
class Hello extends React.Component {
    fn () {
        console.log('Laala Lala Lala')
    }

render () {
      return <ul>
            <p>Click the button to print the information</p>
            <button onClick={this.fn}>Point me</button>
        </ul>
    }
}
const app = (
    <div>
        <Hello />
    </div>
)

reactDom.render(app, document.getElementById('root'))

  What should I pay attention to when writing binding events?

  • The event name is a small hump naming format

  • Supplement methods in classes

  • this.fn do not put parentheses: onclick = {this. Fn()} call fn() first, and then treat the execution result of FN as the handler of click event

  • Don't forget to write this

Event object

In react, it is obtained through the formal parameters of the event handler function. The event object is obtained through the parameters of the callback function.

List:

  handleClick(e)=> {
    e.preventDefault()
    console.log('Click event triggered', e)
  }
	render() {
  	return (<div>
            <button onClick={(e)=>{console.log('The button clicked', e)}}>Button</button>
    				<a href="http://Itcast. CN / "onclick = {this. Handleclick} > check it out</a>
  			</div>)  
  }
}

Event handling - this points to the problem

Let's look at the pointing exception of this through one end of the code

class App extends React.Component {
  state = {
    msg: 'hello react'
  }
  handleClick() {
    console.log(this) // What's this here?
  }
  render() {
    console.log(this) // What's this here?
    return (
      <div>
        <button onClick={this.handleClick}>Point me</button>
      </div>
    )
  }
}
  •   this in the render method points to the current react component.
  • this in the event handler points to undefined

So why is this happening?

  • The functional function call mode of the event handler. In strict mode, this points to undefined
  • The render function is called by the component instance, so this in the render function points to the current component

Namely:

  • Inside class, the local strict mode use strict is enabled, so this does not point to window undefined
  • In onClick={this.fn}, this.fn is not called through the instance of the class, so the value is undefined

Specific event handling - this pointing problem can be referred to Good programmers share React-010 this point of event handling function good programmers' IT blog CSDN blog

Common this pointing solutions:

  • Function.prototype.bind()
  • Arrow function
  • class instance method [recommended]

For specific use, please refer to the above link address

 

Posted by hessodreamy on Sat, 06 Nov 2021 17:27:53 -0700