Link to PDF of this blog: pan.baidu.com/s/1E_E4RqZU… Extraction code: H77D

Learn notes on the Way to React: Learn Notes on the Way to React

Github source code: React_learning

2.1 JSX

2.1.1 JSXIntroduction to the

JSX is a JavaScript extension syntax for describing uIs. React uses this syntax to describe component UIs.

2.1.2 JSXgrammar

1. Basic grammar

The basic syntax of JSX is the same as that of XML, which uses pairs of tags to form a tree structure of data.

const element = (

Hello, world!

)

2. Label type

Two label types:

(1) DOM tags (div, SPAN, etc.) must start with a lowercase letter

React Component type labels. The first letter of the component name must be uppercase

React determines whether to render a DOM tag or a React component tag based on the case of the initial letter.

3. JavaScript expression

The essence of JSX is JavaScript. Using JSX expressions in JSX requires wrapping the expression in {}.

Expressions are used in the following scenarios:

  1. Assign values to tag attributes through expressions
const element = <MyComponent foo={ 1 + 2} / >
Copy the code
  1. Define child components through expressions

 

const todos = ['item1', 'item2', 'item3'];

const element = {

    <ul>

        {todos.map(message => <Item key={message} message={message} />)}

    </ul>

};
Copy the code

= is the way functions are defined in ES6. Map is an array traversal where Message is the argument to the arrow function, key is the index, and message is the value corresponding to toDOS. Here the array todos is iterated through in HTML code.

In addition, only JS expressions can be used in JSX, not multi-line JS statements. JSX can replace the if statement with the trinary operator or the logical and (&&) operator.

4. Label attributes

1. When JSX tags are DOM tags, JSX also supports attributes supported by DOM tags. Some attribute names are changed, for example, the class is className. Event attribute names are in camel format.

2. If the JSX tag is of the React component type, you can customize the attribute name of the tag.

5. Comments

JSX comments need braces “{}” to enclose /**/.

2.1.3 JSXIs necessary

JSX is not required in the Book The React Way To Advance.

2.2 component

2.2.1Component definition

There are two ways to define components: using ES6 classes (class components) and using functions (function components).

Use class to define two conditions that a component satisfies:

  1. Class inherits from react.component
  2. You must customize the Render method inside the class, which returns the React element that represents the component’s UI.

Using reactdom.render () to mount the PostList to the DOM node of the page requires the reactdom.render () library to convert the virtual DOM node represented by the component to the browser’s DOM node.

import React from "react";

import ReactDOM from "react-dom";

import PostList from "./PostList";



ReactDOM.render(<PostList />, document.getElementById("root"));
Copy the code

 

2.2.2Components of the props

The props of a component is used to pass data or methods from the parent component to the child component for use by the child component.

Props is a simple object that contains properties that are used by components as JSX tags. Here is a declaration that uses the User component as JSX as JSX tag:

<User name='React' age='4' address='America' >



props = {

    name: 'React',

    age: '4',

    address: 'America'

}
Copy the code

 

  {data.map(item =>

    <PostItem

      title={item.title}

      date={item.date}

      author={item.author}

   />

  )}
Copy the code

This is the code that uses PostItem in the class component PostList to iterate over the elements in the data array and return an array of the same size (containing the title, Author, and date attributes) to be displayed in the UI.

2.2.3Components of the state

A component’s state is the internal state of the component, and changes in state are ultimately reflected in changes to the component’s UI. Define the initial state of the component in the constructor with this.state and change the state of the component by calling the this.setState method.

constructor(props){ super(props); this.state = { vote: 0 }; } handleClick(){let vote = this.state.vote; vote++; this.setState({ vote:vote }); }Copy the code
  1. The React component is initialized by calling the constructor method of react.component.props.
  2. Constructor defines the initial state of the component via this.state;
  3. The render method defines a response function that handles the click event, and calls this.setState internally to update the component’s likes.

UI = Component(props,state)

The React component uses both props and state to render the component UI. Props is the interface to the component. It is read-only. The component uses Props to receive data from the external. State is the internal interface of the component. It is variable. The internal state of the component is reflected by state.

2.2.4Stateful components and stateless components

State is used to reflect the change of the internal state of a component. If the internal state of a component is unchanged, such a component is called stateless. The reverse is called a stateful component.

Stateless components can be defined using functions in addition to the ES6 class approach. A function component takes props as an argument and returns the React element structure representing the component’s UI.

function Welcome(props){

    return <h1>Hello, {props.name}</h1>;

}
Copy the code

Stateful components focus on the business logic of stateful business changes, while stateless components focus on rendering component UI.

2.2.5Properties Checksum default properties

React provides the object ProTypes to verify the types of component properties. ProTypes contains all possible types of component properties and verifies component property types by defining an object whose key is the component property name and val is the corresponding property type.

A good way to know the structure of an object or the type of a data element is to use protypes.shape or protypes.arrayof. Call isRequired on the type property of ProTypes if the property is a required property of the component, that is, one that must be passed in when using a component.

PostItem.propTypes = {

  post: PropTypes.shape({

    id: PropTypes.number,

    title: PropTypes.string,

    author: PropTypes.string,

    date: PropTypes.string,

    vote: PropTypes.number

  }).isRequired,

  onVote: PropTypes.func.isRequired

}
Copy the code

As shown in the code above, post and onVote are required properties in the PostItem component.

React also provides the ability to specify default values for component properties, which is implemented through the component defaultProps.

2.2.6Component style

1. External CSS style sheets [preferred]

This approach is similar to using external CSS files when developing Web applications. CSS style sheets define element styles based on selectors such as HTML tag type, ID, class, etc. Only difference: React uses className instead of class as selector.

Style sheet introduction:

  1. Use components in HTML pages introduced by tags
  2. Treat the stylesheet file as a module and import it as any other component in the component that uses the stylesheet

Note the class name conflict

Inline style

2.2.7Components and elements

The React element is a plain JS object that describes what the interface looks like through a DOM node or the React component. JSX syntax is used to create React elements.

<div className='foo'>

    <Button color='blue'>

        OK

    </Button>

</div>
Copy the code

Button is a custom React component.

The React component is a class or function that takes attributes as input and returns a React element. The React component is composed of several elements. The React component relates to the React element in the following example:

class Button extends React.Component{

    render(){

        return (<button>OK</button>); }} // In JSX we use the component Button, which represents a react element of the component Button const Button =<Button />; Button class extends React.Component{render(){return ();<div>

                {button}

            </div>); }}Copy the code

 

2.3 Component life cycle

2.3.1Mount the stage

In this phase the component is created, initialized, and mounted into the DOM to complete the first rendering of the component. The lifecycle methods called in turn are: Constructor, componentWillMount, Render, componentDidMount.

  1. constructor

This is the ES6class constructor, which is called when a component is created. If the parent component does not pass in properties and the component defines default properties, then the props parameter refers to the default properties of the component. Constructo is typically used for things like initializing the state of a component and binding time handling methods.

  1. componentWillMount

This method is called before the component is mounted into the DOM and is called only once. This is rarely used in a real project because you can advance this method to constructor. Calling this.setState in this method does not cause the component to be rerendered.

  1. render

This is the only method necessary to define the component (other lifecycle methods of the component can be omitted). In this method, a React element is returned, based on the props and state of the component, to describe the UI of the component. Normally, the React element is defined using JSX syntax. Note: Render doesn’t do the actual rendering of the component, it just returns a description of the UI, and React itself does the actual rendering of the page DOM. Render is a pure function and cannot perform any side effects in this method.

  1. componentDidMount

Called after the component has been mounted into the DOM, and only once. The DOM structure is now available. This method is also typically used to request data from the server side. Calling this.setState in this method causes the component to be rerendered.

2.3.2Update the stage

After a component is mounted into the DOM, the component’s props or state can cause the component to update. When the render method of the parent component is called, the component will be updated every time the render method of the parent component is called, regardless of whether the props are changed. Component updates caused by State are triggered by a call to this.setState to modify the component State. The component update phase calls the declaration cycle methods in turn: compoentWillReceiveProps, ShouldComponentWillUpdate, componentWillUpdate, Render, and componentDidUpdate.

  1. compoentWillReceiveProps(nextProps)

This method is only called during component updates caused by props. Component updates caused by State do not trigger the execution of this method. The nextProps argument to the method is the new props that the parent component passes to the current component. Therefore, it is often necessary to compare nextProps and this.props to determine whether to execute the logic after the props changes, such as calling this.setState to trigger a re-rendering of the component based on the new props.

  1. ShouldComponentUpdate (nextProps nextState)

This method determines whether the component continues the update process. Method returns true, the component continues the update process; When false is returned, the update process stops. Subsequent methods will not be called to you. The result of this method is usually determined by comparing the nextProps and nextState with the props and state of the current component. This method can be used to reduce unnecessary rendering of marshalling to optimize component performance.

  1. ComponentWillUpdate (nextProps nextState)

This method is executed before the component render call, can be executed before a component update occurs, and is rarely used for some work.

  1. ComponentDidUpdate (prevProps prevState)

The component is called after the update and can be used as a place to manipulate the POST-update DOM. The two parameters of this method represent the props and state of the component before it is updated.

2.3.3Unloading phase

The process by which a component is unmounted from the DOM. This process has only one lifecycle method: componentWillUnMount. This method is called before the component is unloaded, where you can do some cleanup, such as cleaning up timers used in the component, to avoid memory leaks.

Finally, note that only class components have lifecycle methods; function components have no lifecycle methods.

2.4 List and the keys

(1) When the list data is multiple groups, the call data will run as a warning (browser F12->Console) : “Each child in an array or iterator should have a unique ‘key’ prop.” The call may result in an error. So the ‘key’ is the primary key in the database, giving a reference to each set of data fetched.

<div>

  <h2>Post a list of</h2>

  <ul>

    {this.state.posts.map(item =>

      <PostItem

        key = {item.id}

        post = {item}

        onVote = {this.handleVote}

      />

    )}

  </ul>

</div>
Copy the code

② Although the key of a list element cannot be repeated, this uniqueness is limited to the current list, not globally unique.

(3) It is not recommended to use indexes as keys, because once the data in the list is rearranged, the index of the data will also change, which is not conducive to React rendering optimization.

2.5 The event processing

1.React element binding events have two caveats:

In React, events are named in a camel case, not in the DOM element. For example: JavaScript onclick to onclick, onchange to onchange.

② The response function that handles the event is assigned to the event property as an object, not as a string in the DOM.

For example, binding a click event to the DOM looks like this (traditional JS writing) :

<button onclick="clickButton()">

    Click

</button>
Copy the code

Binding a click event to the React element looks like this:

class App extends Component { clickButton(){}; //clickButton render() {return ()<div>

                <button 
Copy the code
Onclick ={this.clickButton}> //clickButton is a function Click</button>

            </div>)}}Copy the code

Do not use the arrow function when the React event handler is used

www.jianshu.com/p/135711298,…).

class ...... {

    constructor(props){

        super(props);

        this.state = { number:0 }

    }

    ......

    <button onClick={(event)= >{console.log(this.state.number)}>Click</button>

}
Copy the code

(2) Use component methods (assign component methods directly to the element’s event attribute, and bind this method to the current object in the class construction)

class ...... { constructor(props){ super(props); this.state = { number:0 }; this.handleClick = this.handleClick.bind(this); } handleClick(event){ const number = ++this.state.number; this.setState({ number:number; }}})...<div>{ this.state.number }</div>

    <button onClick={ this.handleClick} >Click</button>

}
Copy the code

Property Initializers will automatically bind this in your class using ES7 property Initializers

handleClick = (event) => {

    const number = ++this.state.number;

    this.setState({

        number:number

    })

}
Copy the code

The first creates a new event handler every time render is called, incurring additional performance overhead; In the second constructor, you need to bind this to the event handler, which makes the code cumbersome when handling multiple events. The third is the recommended method, which requires neither manual binding of this in constructors nor the worry of function duplication caused by repeated component rendering.

2.6The form

2.6.1 The controlled components

If a form element’s value is managed by React, it’s a controlled component. React controls things slightly differently for different form elements. Here are three ways to control long-used form elements.

1. Text box The text box contains input elements and textarea elements of type TEXT. They are controlled by setting the value of a form element through its value attribute, listening for changes in value through the form element’s O ‘Nchange event, and synchronizing the changes to the State of the React component.

import React,{Component} from 'react'; export default class Demo1 extends Component{ constructor(props){ super(props); this.state = {name:'',password:''}; HandleChange (event){const target = event. Target; this.setState({[target.name]: target.value}); } handleSubmit(event){// Response function console.log('login successfully'); event.preventDefault(); } } render(){ return(<form onSubmit={ this.handleSubmit} >

                <label>User name:<input type="text" name="name" value={this.state.name} onChange={this.handleChange}/>

                </label>

                <label>Password:<input type="password" name="password" value={this.state.password} onChange={this.handleChange}/>

                </label>

                <input type="submit" value="Login"/>

            </form>)}}Copy the code

When the user changes the value of the form element, the onChange event is triggered. The corresponding handleChange handler synchronizes the change to the state of the component. The new state triggers the re-rendering of the form element. To control the state of form elements.

  1. List The list select element is the most complex form element. It can be used to create a drop-down table. React determines which option element is selected by defining the value attribute on the SELECT. In this way, control of the select element only needs to be changed on the SELECT element, not the Option element.
  2. Checkboxes and checkboxes Check boxes are of type checkbox input elements, and checkboxes are radio input elements. The values of the checkboxes and checkboxes do not change; what needs to change is their checked state. The React control property becomes checked

 

 

P48 Code class diagram and description of relationships

 

PostItem and PostList both inherit from Component, and PostList is related to each other

{this.state.posts.map(item => 

    <PostItem key = {item.id} post= {item} onVote={this.handleVote} onSave={this.handleSave} /> )}
Copy the code

OnVote uses handleVote (id) to filter posts based on their ID, return the new posts object, and update state. OnSave uses handleSave(Post), but uses PostItem property prop, Filtering out the current post PostItem rendering is the title (handled by the handleTitleChange method for changes in

 

2.6.2 Uncontrolled component

Uncontrolled components may seem to simplify the process of manipulating form elements, but this approach breaks the consistency of React’s component state management and leads to problems that are difficult to troubleshoot. Therefore, they are not recommended.

2.7 The summary of this chapter

This chapter describes the main features and usage of React in detail. React uses JSX syntax to declare the UI, encapsulating the UI and its logic in the same JS file. The React component is the core of React. It performs rendering according to its external interface props and internal interface State. Using a component requires an understanding of its lifecycle, and with different lifecycle approaches, components can implement complex logic. When rendering, pay attention to the use of keys, and when handling events, pay attention to the writing of event names and event handlers. Finally, it introduces the use of form elements, which can be divided into controlled groups and uncontrolled components. In addition, in engineering projects, pay attention to the division of stateful and stateless components to properly use props and state.