React

Summary of the React

React is a great JavaScript library for building user interfaces. React is primarily used to write HTML pages, or to build Web projects. Components are the most important part of React. React leverages the power of the JS language itself to write UL, instead of building wheels to enhance HTML. Data-driven View (UI User Interface)

Create the React

Install two react packages: NPM I react react-dom 2 Create a react element

    const e1 = React.createElement('h1', {title:'title'},'hello React')
    // Return the React element
    // First argument: the name of the React element to be created
    // The second argument is the React element attribute
    // The third and subsequent arguments: children of the React element
Copy the code

Second :(usually used this way)

    ReactDOM.render(el,document.getElementById('root'))
    // First argument: React element to render
    // The second parameter: the DOM object, which specifies where to render to the page
Copy the code

Use of React scaffolding

NPM start = NPM start = NPM start = NPM start = NPM start = NPM start = NPM start = NPM start = NPM start = NPM start

    import React from 'react';
    import ReactDOM from 'react-dom';
Copy the code

JSX(core content of React)

JSX, short for JavaScript XML, represents the code advantages of writing XML(HTML) format in JavaScript code: declarative syntax is more intuitive and has the same structure as HTML, reducing learning costs and improving development effectiveness

Create react elements using JSXconst title = <h1>Hello JSX</h1>Reactdom.render (title,document.getElementById('root'))
Copy the code

To write js logic inside JSX, write js inside curly braces {}, and enclose embedded expressions with curly braces {}

    const name = 'Tom'
    const tittl = (<div>Hello {name}</div>)
    // Output Hello Tom
Copy the code
JSX list rendering

If you render a set of data, you can use the map() method of the array

    cosnt arr = [1.2.3]
    const list = (
     <ul>
      {arr.map(item => <li key='item.id'>{item}</li>} / /<li>1</li><li>2</li><li>3</li>When rendering a list, we should add a key attribute. The value of the key attribute should be unique: map() iterates over each person, and we should add the key attribute. We should try to avoid using the index number as the key</ul>
    )
Copy the code
Style handling for JSX

< span style = ‘title’ > < span style = ‘title’ > < span style = ‘title’ > < span style = ‘title’ > < span style = ‘title’ > < span style = ‘title’ > < span style = ‘title’ >

React Component Basics

1. Introduction to the React component

Components are long or repetitive code broken down into relatively clear, short components, and then put together to achieve the full page function, the benefit of componentization is easy for the writer to read and modify the characteristics: reusable, independent, can be combined

2. Two ways to create the React component

Function components: Create components using js functions (or arrow functions)

    functionn Hello() {
      return(
        <div>This is my first function component</div>
      )
    }
    ReactDOM.render(<Hello />,root);
    //const Hello = () => 
      
this is my first function component
// Component must start with uppercase, return must also be a value, if you want nothing to render null // Render the function component: use the function name as the component tag name // The label in React must be closed // To enable the component to be referenced and used by other files, use export default Hello; Throw the component out Copy the code

Class components: Components created using ES6’s class

    class Hello extends React.Compinent {
      rander() {
        return <div>Hello Class Component</div>
      }
    }
    ReactDOM.render(<Hello />,root)
    //1: Class components must also be capitalized
    //2: Class components should inherit from the React Component parent class so that they can use methods and properties provided in the React Component parent class
    //3: Class components must provide the render() method
    //4: the render() method must have a return value representing the structure of the component
Copy the code

It is common to place each component in a separate JS file: Components, as an individual, are usually placed in a separate JS file, which can be easily read or modified to create a component file hello.jsx, Import Hello from ‘./Hello’; import Hello from ‘.

3.React event handling

Syntax: on+ event name ={event handler}, for example: onClick={() => {}}; React events are named after humps, such as onMouseEnter and onFocus

    class App extends React.Component {
    // Click on the button to trigger the event program, written in the onClick event, when the button is clicked to print the click event triggered
    handleClick() {
    console.log('Click event trigger');
    }
    render() {
    return(
    <button onClick={this.handleClick}>Am I</button>
    // Use the name of the function component directly, so write this in the class)}}Copy the code

Event objects in React are called composite events (objects). Composite events are compatible with all browsers, so you don’t have to worry about cross-browser compatibility

    function handleClick(e) {
      e.preventDefault()
      console.log('Event Object', e)} <a click ={handleClick}>Copy the code

Function components are called stateless components, and class components are called stateful components. In other words, data function components have no state of their own, but are only responsible for displaying data (static). Class components have their own state, which is responsible for updating the UI and making the page “move”

State and setState() in components

The value of state is an object, indicating that a component can have multiple data setState() to modify the state. State is a mutable syntax: This.setstate ({data to be modified}), do not change the value in state directly, just wrong

    class App extends React.Component {
      state = {
      count: 0.test:'1'
      }
    render() {
    return(
    <div>
      <div>Count: {this.state.count}</div>
      <button onClick={()= >{this.setstate ({count:this.state.count+1 // change only local content, not reload the entire page, reduce run, data-driven view (UI)}}>+1</button>
    </div>)}}Copy the code

Detach event handlers from JSX: Detach the JS logic code into separate methods to keep the JSX structure clean

Event binding to this
  1. Arrow function: Take advantage of the fact that the arrow function itself is not bound to this. The arrow function does not point to this, it will point to the outer layer, so this in the method can point to the outer instance.

Such as: Bind this to the component instance in the event handler. As long as the function bind(this), whoever calls it will point to the bound this. Bind the: this. event method = this within constructor. Event method. Bind (this); OnClick = (() => {constructor}) onClick = (() => {constructor})

Form components

    // Controlled components
    state = {txt:' '}
    // Add a state to the form element value (control the source of the form element value)
    <input type = ”text“ value={this.state.txt} onChange = {e= > this.setState{txt: e.target.value}}/>
    // Bind the change event to the form and set the value of the form element to the value of state.
    
Copy the code

Uncontrolled component

Component communication

The component is closed, and the function of receiving external data is props. The function of the props is to receive the data passed to the component

    <Hello name="jack" age={19} / >// Use curly braces for non-string data
    function Hello(props) {
    console.log(props)
    return(
    <div>Received data: {props. Name}</div>)}// The function component uses props to receive data, and the class component uses this. Props to receive data
Copy the code

Features of props;

  1. You can pass any type of data to a component
  2. Props is a read-only object. It can only read the values of properties. It cannot modify the object
  3. When using a class component, if you write a constructor, alter to pass the props to super(). Otherwise, you cannot get props in the constructor.
Context(passing parameters across groups) used when multiple components
  1. React.createcontext () creates a Provider and a Consumer component
    const = {Provider , Consumer} = React.createContext()
Copy the code
  1. Use the Provider component as the parent node
    <Provider>
    <div className = "App">
    <Child />
    </div>
    </Provider>
Copy the code
  1. Set the value attribute to indicate the data passed by yo
    <Provider value="pink">
    </Provider>
Copy the code
  1. Call the Consumer component to receive the data and write it to the group price that wants to receive the data
    <Consumer>
    {data= > <span>The data argument indicates that data was received -- {data}</span>}
    </Consumer>
    //data Receives the data passed by value
Copy the code
Props in-depth
  1. The children attribute: represents the component tag child node. This attribute is available only when there are children in the component tag. This value can be any value, and can be captured by using props.
  2. Props validation: Allows you to specify the props type, format, and so on when creating a component.
    App.propsType = {
    colors:PropsType.array// Specify props as an array
    }
    //1. Installation package prop-types(NPM I props-types)
    //2. Import the prop-types package
    //3. Add a validation rule for the props of the component using the component name.proptypes ={}
Copy the code

Common types: array, bool, func, number, object, string. 2.React Element type: Element 3. Required: isRequired

The lifecycle of the component

Component lifecycle: Only class components have a lifecycle from when a component is created to when it is mounted to run on a page to when it is unloaded

Three phases of the life cycle
  1. Create time (mount stage)

Construcot ()->render()->componentDidMount()

  1. update

Timing: 1.setState() 2.forceUpdate() 3. (function_componentdidupdaate) (function_componentDidupdaate) (function_componentDidupdaate) (function_componentDidupdaate) (function_componentDidupdaate)

3. Uninstall execution time: Component disappears from page

High order component

High-order components are packaged in order to realize state logic reuse. After the packaging, the components will have functions that they do not have

  1. Creates a function whose name convention begins with with
  2. Specifies function arguments that should start with an uppercase character (as the component to be rendered)
  3. Create a class component inside the function, provide reusable state logic code, and return the class component
  4. In this component, the parameter component is rendered and the state is passed to the parameter component via props
  5. The higher-order component is called, the component to be enhanced is passed in, the enhanced component is picked up by the return value, and it is rendered into the page
    function withMouse(WrappedComponent){
      calss Mouse extends React.Component {}
      return Mouse
    }
    
    // In the Mouse component's render method:
    // Render the component and pass the state to the parameter component via props
    return<WrappedComponent {. this.state} / >
Copy the code

In general, React uses the component name as the displayName. Solution: Set display for a higher-order component so that you can distinguish between different component Settings during debugging:

    Mouse.dispalyName = 'WithMouse${getDisplayName(WrappedComponent)}'
    
    function getDisplayName(WrappedComponent) {
    return WrappedComponent.displayName || WrappedComponent.name/ / Component name | | 'Component'
    }
Copy the code

High order component pass props lost solution: when rendering WrappedComponent, the state and this. Props to components together

<WrappedComponent{... this.state} {... this.props} />Copy the code
The usual way to introduce images in React
React introduces images in two ways:1.throughimportIntroduction of picturesimport kill from".. / images/jisha. PNG ";// Import the imageThen call <img SRC = {kill} Alt ="" />//img is a single tag. The tag should be closed
2.Use in SRCrequireMethod <img SRC = {require(".. /images/jisha.png").default} alt = "">

Copy the code

The React principle

SetState ()

  1. Update the data

Note: When using this syntax, the following setState() does not rely on the preceding setState(). SetState () can be called multiple times, and will only trigger a rerender. The recommended syntax is setState((state,props) => {}. Syntax parameter state: indicates the latest state parameter props: indicates the latest props

    this.setState((state,props) = >{
    return(
    count:state.count+1)})console.log(thsi.state.count)/ / 1
Copy the code

SetState ((state,props) =>{},callback)

    this.setState(
    (state,props) = > {},
    () = > {console.log("This callback will execute immediately after the status update.")}// The callback function
    )
Copy the code

Component update mechanism

Updating a parent component causes the child component to be updated as well

Component Performance optimization

  1. Lighten state: Store only data related to component rendering (e.g. count/ list data /loading, etc.)

Do not place data that does not need to be rendered in state, such as timer ID, etc. For data that needs to be used in multiple methods, it should be put in this 2. How to avoid unnecessary rerendering: Fix: use the hook function shouldComponentUpdate(nextProps,nextState)) — nextState is the latest state. Return true for rerendering and false for not rerendering. (shouldComponentUpdate->render) 3. Pure component 78 sets, 79 sets not seen

Virtual DOM and Diff algorithm

In React, partial updates are realized through virtual DOM and diff algorithm, and only the changed contents are rerendered. Diff algorithm is to recurse DOM to find differences and rerender the changed parts