This is the 16th day of my participation in the August More Text Challenge. For details, see: August More Text Challenge

📢 Hello everyone 😪, I’m Xiao Cheng. Recently, I’ve been learning React, mini program, reading JS elevation, and organizing Node notes. This is the second article about React, and the first framework for my learning

📢 may your life be bright and lovely

1. Use of components

When an application is implemented in a multi-component manner, the application is a componentized application

Note:

  1. The component name must be uppercase

  2. A virtual DOM element can have only one root element

  3. Virtual DOM elements must have closing tags < />

The basic flow of rendering class component labels

  1. Component instance objects are created inside React

  2. Call render() to get the virtual DOM and parse it into the real DOM

  3. Inserts inside the specified page element

Functional components

//1. Create a function that may or may not have parameters, but must return a virtual DOM with a return value
function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}
//2. Render
ReactDOM.Render(<Welcom name = "ljc" />.document.getElementById("div"));
Copy the code

The above code goes through the following steps

  1. We callReactDOM.render()Function, and pass<Welcome name="ljc" />As a parameter.
  2. The React callWelcomeComponent and will{name: 'ljc'}Pass it in as props.
  3. WelcomeComponents willHello, ljcElement as the return value.
  4. The React DOM efficiently updates the DOM toHello,ljc.

2. Class components

class MyComponent extends React.Component {
    state = {isHot:false}
    render() {
        const {isHot} = this.state
        return <h1 onClick={this.changeWeather}>It's {isHot? 'Hot ':' cool '}</h1>
    }
    changeWeather = () = >{
        const isHot = this.state.isHot
        this.setState({isHot:! isHot}) } } ReactDOM.render(<MyComponent/>.document.querySelector('.test'))
Copy the code

This thing is not simple at the bottom, the direction of this really need to learn

Problems encountered in the optimization process

  1. The this in the render method of the component is the component instance object
  2. Component custom methods with strict mode enabled, this points toundefinedHow to solve
    1. Change this with bind
    2. It is recommended to use the arrow functionthisPoint to the
  3. State data cannot be directly modified or updated

3. Other knowledge

Components that contain form elements are divided into uncontrolled rents and controlled components

  • Controlled component: The input component of the form component follows the input and stores the content in the state (updated at any time)
  • Uncontrolled components: Input components to form components the contents of the components are stored in state only when required (ready-to-use)

Component instance properties

1. state

React treats a component like a State machine. By interacting with the user, implementing different states, and then rendering the UI to keep the user interface consistent with the data.

In React, you simply update the component state and then rerender the UI based on the new state (without manipulating the DOM).

Simply put, this is the state of a component, that is, the data stored by the component

Class component

Use this. State to call the value in state

Define state in a class-like component

  • Init in the constructorstate
  • Add attributes to the classstateTo initialize the

Change the state

In a function of a class-like component, modify the state value directly

this.state.weather = 'cool'
Copy the code

The page is rendered by the render function

The reason is that state is not recommended in React and is not allowed to be changed directly. Instead, we use the setState() method on the prototype object of the class

setState()

this.setState(partialState, [callback]);
Copy the code
  • partialState: Part of the object’s state to be updated
  • callback: callback function after updating the state

There are two ways to write it: Write method 1

this.setState({
    weather: "Cool"
})
Copy the code

Method 2:

// Pass a function that returns the object x needs to be changed to, taking the current state
this.setState(state= > ({count: state.count+1});
Copy the code

SetState is a merge operation, not a replacement operation


  • In the implementationsetStateAfter that, React is automatically called oncerender()
  • render()Is executed 1+n (1 is the automatic call at initialization, n is the number of status updates)

2. props

Unlike state, which is the state of the component itself, props is the incoming data from outside

Class component

We can use this. Props to get the props of a valued component:

  1. By passing the value on the component label, you get the passed value in the component
  2. In the constructorpropsParameterprops
  3. You can set them separatelypropTypes 和 defaultPropsTwo properties to operate separatelypropsSpecification and default values, both of which are added directly to class-like componentsA prototype objectSo it needs to be addedstatic)
  4. At the same time you can go through.Operator to simplify

In functional components

Functions use props as arguments (props)

Function component props

  1. Passed in the component labelpropsThe value of the
  2. The parameters of the component function areprops
  3. rightpropsLimits and defaults are also set on the prototype object

3. refs

Refs provides a way to access DOM nodes or React elements created in render methods.

When we normally operate on nodes, we need to use the DOM API to find elements, but this goes against the React philosophy, hence refs

There are three ways to operate REFS, which are:

  • String form
  • The callback form
  • createRefIn the form of

The value is a string refs

It’s obsolete, but it still works, and it works very well

Refs in callback form

The component instance’s ref property passes a callback function c => this.input1 = c (short for arrow function), which stores a reference to the DOM node in the instance’s properties and can be used through this.input1

Method of use

<input ref={c= > this.input1 = c } type="text" placeholder="Click the button for data."/>
Copy the code

I understand it

C receives the current node as an argument, and the value of ref is the return value of the function, which is this.input1 = c, so it is assigned to input1 in the instance

CreateRef form

React provides an API that automatically puts this DOM element into an instance object

Let’s start by adding the REF attribute to the DOM element

<input ref={this.MyRef} type="text" placeholder="Click and pop up" />
<input ref={this.MyRef1} type="text" placeholder="Click and pop up" />
Copy the code

Create a React container using the API and assign a DOM element to an instance object whose name is current.

MyRef = React.createRef();
MyRef1 = React.createRef();
Copy the code

Note: dedicated, annoying, a node to create a container

/ / call
btnOnClick = () = >{
    // After creation, pass the node to current
    console.log(this.MyRef.current.value);
}
Copy the code

Note: we don’t want to overuse the ref, if the element that happens to occur at the time is the element that needs to be operated on, we can use the event object instead. I don’t know what’s wrong with overuse, maybe a bug

4. Event handling

  1. React uses custom events instead of native DOM events

  2. React events are handled via event delegate (for efficiency)

  3. The DOM element object can be obtained through the event. Target of the event to minimize the use of refs

Higher order functions

About this part of knowledge, the previous notes have been recorded, I am really great

Linking higher order functions, AOP, partial functions, and currying are well documented and feel good