What is the react

React is a JavaScript library (declarative, component-based visual library) for building user interfaces. It’s a library in itself. Why do we call it a framework? After React combined with Redux, react-Router could develop regular unit applications.

What are the characteristics

  • Virtual DOM
    • In Web development, DOM changes are always displayed on the UI in real time, so we need to manipulate the DOM, so complex and frequent manipulation of the DOM can cause performance problems;
    • How to manipulate high-performance complex DOM is now an important measure of the front-end developer’s skill;
    • React implements a SET of DOM apis in JavaScript in the browser. The underlying DOM Diff algorithm is used to update different parts, greatly improving performance.
  • componentization
    • The so-called component refers to the completion of a specific function, independent reusable code;
    • Today’s developers tend to break large applications into components based on components, with each component responsible for its own function.
    • Advantages: Reusable;
  • declarative
    • React automatically builds websites based on data
    • Using declarative specification, usingReactDOM.render()To declare
  • flexible
    • Works well with known libraries or frameworks: Redux, mobileX, etc
  • efficient
    • By emulating the DOM, there is less DOM manipulation
  • objectification
    • Encapsulating the various components and data flows within a component can be treated as a whole rather than as parts

How to choose Vue & React

  1. React is more flexible and collaborative than Vue
  2. Vue has a rich Api and is easy and fast to implement
  3. Vue’s cost of getting started and learning is relatively low
  4. React is recommended for large and complex projects

Build the basic React project

Front-end environment: Node, create-react-app

If you do not have Node, go to nodejs.org/zh-cn/downl… Download long-term support version, download complete foolproof installation; Create-react-app is installed as follows

#Check node and NPM versions. If the following information is displayed, the installation is successful
$: node -v
v14.15.4
$: npm -v
6.14.7
#Install the React scaffold builder globally
$: npm i -g create-react-app
C:\Users\A\AppData\Roaming\npm\create-react-app -> C:\Users\A\AppData\Roaming\npm\node_modules\create-react-app\index.js
+ [email protected]
Copy the code

Create-react-app react-demo will automatically create the react-demo directory in the current directory.

#Go to the react-demo directory
$: cd react-demo
#If there is no node_modules directory, perform this operation to download dependencies, otherwise skip
$: npm i
#Executing internal applications
$: npm start
Copy the code

Once executed, we can see the React website for more information

The available scripts

npm start

Run the application in development mode. Open http://localhost:3000 and view it in your browser. If you edit, the page will reload. You will also see any errors in the console.

npm test

Start the test runner in interactive monitor mode.

npm run build

Build the application for production into the Build folder. It bundles React correctly in production mode and optimizes the build for best performance. Minimize build, file name contains hash. If necessary, you can enable class and function names for profiling.

npm run eject

Json file. If you are not satisfied with your build tools and configuration choices and are familiar with your own webpack, you can execute eject (note: this is a one-way operation. Once eject, it cannot be returned). This command removes a single build dependency from the project, and then copies all configuration files and dependencies to package.json, with additional scripts and config directories in the directory.

hello World

After a new project, the directory structure does not meet our development needs, so we need to make some changes:

// delete unnecessary files from SRC. CSS files into a static file directory ├ ─ SRC | ├ ─ App. Js | ├ ─ index. The js | ├ ─ logo. The SVG | ├ ─ tests / / test file | ├ ─ components / / put components | ├ ─ assets / / static file | | ├ ─ js | | ├ ─ images' | | ├ ─ CSS | | | ├ ─ App. CSS | | | └ index. The CSS ├ ─ scripts ├ ─ public ├ ─ configCopy the code

SRC app.js file to see Hello World:

import React from "react";
import "./assets/css/App.css";

/ / the root component
class App extends React.Component {
  render() {
    return (
      <div className="App">
        <h2>Hello World</h2>
      </div>); }}export default App;
Copy the code

JSX,

What is the JSX

JSX (Javascript and XML) is an extensible markup language for Javascript. React advocates all in JS. It doesn’t mandate JSX, but it does recommend it.

From a code point of view, HTML in JS files, at first, may be considered to violate the principle of style, behavior, and action separation; But let’s think about it carefully, in fact, Html, CSS, JS is just a file management, and there is no logical separation.

Now, why can’t we manage them in a file? In fact, it can be seen as encapsulation of macro code. A component is a module that implements style functions, so implementing JSX is not a step backward, but a syntactic sugar.

Note: JSX is a React technology, not a new language.

import React from "react";
import "./assets/css/App.css";

function App() {
  return (
    <div className="App" tabIndex="1" dataId="1">
      <h2>Hello World</h2>
    </div>
  );
}

export default App;
Copy the code

Why can only use the className attribute for style attribute names of elements in JSX? Because class is a keyword in javascript, you have to use className, but other attributes are also used to follow the rules of javascript using camel name or avoid keywords using other names.

JSX principle

DOM element structure in the page can be described by javascript objects, such as tag names, attributes, child elements, event objects and other information; In JS everything is an object, the object is characterized by attributes and methods. Let’s continue with the code:

<div title="Hello">
  <h2 className="App">Hello World</h2>
</div>;
// webpack+ Babel ------>
React.createElement(
  "div",
  { title: "Hello" },
  React.createElement("h2", { className: "App" }, "Hello World"));/** * react. createElement(tag name, attribute object, child element) */
Copy the code

The essence of JSX syntax is that it is implemented in the form of react. createElement and does not render the HTML code directly to the page.

This reminds us of the document.createElement method in JS, which is similar to the React method. At a deeper level, they’re all built on prototype objects. React itself is an instantiated object.

From the above code, the use of JS object code will be more cumbersome, the structure is not clear, so JSX writing more visual.

JSX specific usage

  • The label
    1. DOM tags: div, p, etc., must start with a lowercase letter.
    2. Custom labels (components) must begin with a capital letter.
  • Inline style
    • Inline styles use objects with property names like hump names;
  • expression
  • Tag attributes
    • Use camel name tags: onClick, tabIndex, className, etc.
  • annotation
  • Extended operator

Take the app.js file as an example:

import React from "react";
import "./assets/css/App.css";

// Click the event call
function handled() {
  console.log(Click trigger);
}

// Components pass values
function User(props) {
  return (
    <div>
      <h2>I am the User component</h2>
      <p>
        {props.name} --- {props.age}
      </p>
    </div>
  );
}

function Component1() {
  const divTitles = "I am a component."; // Attribute variables
  const divStyles = {
    // Inline style
    color: "red".fontSize: "26px"};let flag = true; // Expression variables

  const props = {
    // Pass in the User component with the extended operator
    name: "XXX".age: 22};return (
    <div style={divStyles} className="App" title={divTitles}>
      <h3>{divTitles} Component1 {flag ? "Expression here" : "none "}</h3>
      <p onClick={handled}>P tags</p>{/* This is the annotation specification */}<User {. props} / >
    </div>
  );
}

class App extends React.Component {
  render() {
    return (
      <div className="App">
        <h2>Hello World</h2>
        <Component1 />
      </div>); }}export default App;
Copy the code

Virtual DOM and non-DOM attributes

What is the Virtual DOM?

In React, the result of render execution is not a real DOM node, but a lightweight JavaScript object called a virtual DOM.

The virtual DOM is a highlight of React, with batching and efficient Diff algorithms.

This allows us to “refresh” the entire page at any time without worrying about performance, and the virtual DOM ensures that only the parts of the interface that actually change are actually DOM manipulated. How the virtual DOM works is virtually unnecessary in actual development, but understanding how it works not only helps you better understand the life cycle of the React component, but also helps you optimize the React application.

Has the website on the Virtual DOM did explanation: zh-hans.reactjs.org/docs/faq-in…

Animated virtual DOM to yylifen. Making. IO/sundries – tr…

Non-dom attributes and how to use them

dangerousSetInnerHTML

In React, dangerousSetInnerHTML is an attribute under the DOM element;

DangerousSetInnerHTML replaces innerHTML in the browser. In React, you must use the dangerousSetInnerHTML method to insert HTML content externally.

IO /qiuliang1/p DangerousSetInnerHTML: Implement codepen. IO /qiuliang1/p…

DangerousSetInnerHTML has 2 layers {}, the first layer {} represents the beginning of JSX syntax, the second is to represent dangerouslySetInnerHTML is an object key-value pair, to ‘__html’ as the key, the value can be a tag can also be a string;

Why not innerHTML

Incorrect use of innerHTML can lead to cross-site scripting (XSS) attacks. DangerousSetInnerHTML The prop name also explicitly alerts us to dangerous use, and its prop value (objects instead of strings) is used to represent cleaned data. Before inserting HTML into a page, you need to make sure the HTML is properly structured and cleaned up. You can do this using a library like DomPurify.

ref

React supports a special REF property that can be attached to any component. This property can be an object created by the react.createref () function, a callback function, or a string (legacy API). When the ref attribute is a callback function, the function takes (depending on the element type) the underlying DOM element or class instance as its argument. This gives you direct access to DOM elements or component instances

Ref’s cannot be used in function components, but can be used in class components and function components.

/ / class components
class Footer extends React.Component {
  render () {
    return (
      <div>
        <h2>I'm a class component</h2>
      </div>)}}// Function components
function User(props) {
  return (
    <div>
      <h2>I am the User component</h2>
      <p>{props.name} --- {props.age}</p>
    </div>)}// Function components
function Component1() {
  // Create a ref
  const userRef = React.createRef()
  // Function components use ref internally
  const inputRef = React.createRef()

  function handled() {
    console.log('Click trigger', userRef);
    /* {current: internal component information} */
    // Focus the input box by clicking the button
    inputRef.current.focus();
  }

  return (
    <div className="App">
      <button onClick={handled}>Click on the I</button>
      <input type="text" ref={inputRef}>
      <User {. props} / >
      <Footer ref={userRef} />
    </div>
  );
}

Copy the code

key

“Key” is a special string attribute that is used when creating an array of elements. The key helps React identify items that have been modified, added, or removed. Each element in the array should be given a key so that the element has a fixed identity.

  • Improve rendering performance
    • We all know that the react virtual DOM is improved by using the diff algorithm. If a key is added to the DOM of array rendering, the DIff algorithm can compare the changed parts more accurately.
    • It is not recommended to use index as the key in array rendering. There are also hidden dangers when adding and deleting the array (the previous data and the re-rendered data can not be established as the key value changes. That would lose the point of the key. It is also the culprit of the data quirks);
  • A unique identifier

Props (properties) introduction and use

What is the props

In react application development, we mostly used component-based development. The most important component in a component is data, which is divided into two types: props, state; The result rendered in a UI is mapped to the corresponding HTML structure in the render method using these two attributes.

By default, props can be an external interface that accepts only external data, and the content is read-only data. If you force changes, an error will be reported. React data flows are one-way. This is also required for reuse of components. If components can be changed internally, unpredictable bugs may occur, which may affect developer debugging.

The components inside are not immutable. We use state to implement changes for props, and we don’t actually change the props value. We use the setState method built in React to change the internal value indirectly.

function User(props) {
  return (
    <div>
      <h2>I am the User component</h2>
      <p>
        {props.name} --- {props.age}
      </p>
    </div>
  );
}

function com() {
  const props = {
    name: "XXX".age: 22};return <User {. props} / >;
}
Copy the code

In the code, the parent component passes in the props property value of the child component. The child component accepts the two data, which is mapped to the corresponding structure by the render function.

Note that render is triggered whenever props or state changes to render the component again.

How to use

Basic usage

The following code includes props and class components, and state for class components:

<User name="XXX" age=""/ >;<Footer name="XXX" age="22" />;

function User(props) {
  return (
    <p>
      {props.name}---{props.age}
    </p>
  );
}
/ / the default value
User.defaultProps = {
  age: 18};/ / class components
class Footer extends React.Component {
  // The constructor function, if not declared, is added by default
  constructor(props) {
    // es6
    super(props);
    // Component internal state setState
    this.state = {
      name1: props.name + "www".count: 0};// this binds the event
    this.handleAdd = this.handleAdd.bind(this);
  }
  // Change the value dynamically
  handleAdd() {
    this.setState((state) = > ({
      count: ++state.count,
    }));
  }
  render() {
    return (
      <div>
        <p>
          {this.state.name1}---{this.props.age}
        </p>
        <button onClick={this.handleAdd}>Since the increase {this. State. The count}</button>
      </div>); }}Copy the code

In the User component, you can pass the props parameter. In the class component, you can pass the this.props. In cases where the parent component does not pass data to the child component, you can use the user.defaultprops method to set the default.

Child component passes value to parent component

The previous section of code is to show the parent component to the child component of the value method, so we now look at a component to the parent of the value method;

We also use the props feature to accept any data type, so we can pass functions:

function getChildData(data) {
  console.log("Receive values of child components", data);
}

/ / class components
class Footer extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0}; } handleApp =() = > {
    this.setState((state) = > {
      count: ++state.count;
    });
    this.props.getChildData(this.state.count);
  };
  render() {
    return <button onClick={this.handleClick}>test</button>; }}class App extends React.Component {
  render() {
    return <Footer getChildData={getChildData} />; }}Copy the code

Function components and class components

  • Function component (functionOnly) :propsStateless components
  • Class components (class) :props, there arestateAnd life cycle, usestateIs a stateful component, or a stateless component

If the class component does not use state and life cycle, it is recommended to use function components instead because function components are relatively efficient. With hooks, function components can also use state, which will not be covered here.

State introduction and application

The core idea of React is componentization. Applications are built from components. The most important concept in components is State.

What is the state

React treats a component as a State machine. Achieve different states by interacting with the user, and then render the UI to keep the user interface and data consistent. React simply updates the component’s state and rerenders the user interface based on the new state (don’t manipulate the DOM).

setState

Let’s use the Footer component again to do a control show hide operation:

class Footer extends React.Component {
  // The constructor function, if not declared, is added by default
  constructor(props) {
    // es6
    super(props);
    // Component internal state setState
    this.state = {
      name1: props.name + "www".count: 0.isShow: true};// this binds the event
    this.handleAdd = this.handleAdd.bind(this);
  }
  // Change the value dynamically
  handleAdd() {
    // the function form setState
    this.setState((state) = > ({
      // Perform calculations based on the current state to ensure that state is up to date
      count: ++state.count,
    }));
    this.props.getChildData(this.state.count);
  }
  /*************** Click control display **************************/
  handleClick = () = > {
    // The object form is setState
    this.setState({ isShow:!this.state.isShow });
  };
  render() {
    return (
      <div>{/* dynamic display */} {this.state-isshow?<h2>I'm show and hide</h2> : ""}
        <p>
          {this.state.name1}---{this.props.age}
        </p>
        <button onClick={this.handleAdd}>Since the increase {this. State. The count}</button>
        <button onClick={this.handleClick}>control</button>
      </div>); }}Copy the code

When we call the handleClick function, we change the state through setState, which recalls the Render method to update the page content.

Also note that setState updates in the React event handler (onClick, onChange) and lifecycle hook functions are asynchronous and do not update components immediately. Instead, it puts the state object in an update queue. Then the new state is extracted from the queue (batch delayed update) and merged into state. Finally, the render function component is triggered to re-render the updated page.

Events that are not React controlled are updated synchronously, such as native JS bound events (setTimeout).

How is the state of the component divided

The props and the state are both components and will affect the final presentation of the component UI. If a component needs to be set with state, there are some rules to be used:

  1. Keep components as little state as possible: UI rendering, data presentation, no complex interactions, pass props through external components, no state (function function components are generally recommended)
  2. Data that changes over time: after a certain period of time, clicking the button changes the state; Page interaction, use state

Compare props with state

  1. State is the component’s own management of data, control of its own state, variable;
  2. Props is an external data parameter that is immutable.
  3. Those with no state are called stateless, and those with state are called stateful.
  4. Use props more than state. That is, write more stateless components.

React component life cycle

ReactThe lifecycle (mount => unload) hook function is component-specific and is used againclassClass component;ReactThe life cycle has three phases: Mount phase => Update phase => Uninstall phase => Error handling (React v16)

Mount the stage

constructor(props)

Constructor also adds super(props) to ensure that props are passed into the component. This method also initializes state and this bindings

constructor(props) {
  // super calls the parent class props
  super(props);
  // The internal state of the component is initialized
  this.state = {
    name1: props.name + "www".count: 0.isShow: true};// this binds the event
  this.handleAdd = this.handleAdd.bind(this);
}
Copy the code

ComponentWillMount (obsolete after V16.3)

This is called before render and only once, but using setState in this method does not cause rerendering (setState is synchronous and does not trigger additional render processing), and has side effects or subscriptions. Anything that this method can initialize can be placed in the constructor method, so it is rarely used

componentWillMount() {
  console.log("Soon to mount")}// About to mount
// Warning: componentWillMount has been renamed, and is not recommended for
// use. See https://reactjs.org/link/unsafe-component-lifecycles for details.
UNSAFE_componentWillMount() {
  console.log("Soon to mount")}Copy the code
  • When using componentWillMount, you can print the result, but the console warns that the method has been renamed and is not recommended. The name will continue to be used with React 17.

  • We use UNSAFE_componentWillMount instead, which is fine. If you add strict mode globally, you still get an error: it is not recommended to use strict mode.

render

The only necessary method that can be omitted except for the rest of the component’s life cycle; The element will not be rendered without this method, which returns a react element (state, props); Not responsible for the actual rendering of the component, just return a description of the UI;

Note:

  • Render must be a pure function that cannot change state (call setState) and cannot perform any side effects that might result in infinite rendering and an infinite loop.

Function:

  • Evaluate props/state to return the corresponding result;
  • throughReact.createElementConvert JSX to a vDOM object model.

componentDidMount

  • When the component is mounted to the DOM, it is called only once, and the real DOM can be retrieved.

  • Reasons for requesting data from the server:

    1. This ensures that when data is obtained, the component is already mounted and dom can be manipulated directly.
    2. Ensure that only one call is made in any case and no request for excess data is sent;
  • It can only be called on the browser side, and the dom tree cannot be generated on the server side;

  • Calling setState in this method causes the component to be rerendered;

  • Function:

    1. You can get the real DOM and data
    2. Data requests and modifications can be made
    3. Manipulation of the real DOM, instantiation of third-party libraries

Update the stage

componentWillReceiveProps(nextProps)

  • This method is only raised during a component update caused by the receiving props. This. setState does not trigger this method;

  • Whenever the render function of the parent component is called, this function is triggered regardless of whether the props passed from the parent component to the child component is changed.

  • The official recommendation is to use getDerivedStateFromProps() instead. This method is as obsolete as componentWillMount, and the important points to note if you want to use it are as follows:

shouldComponentUpdate(nextProps)

  • Should this component be updated, if updated, it will rerender and trigger render; The React component is used to tell the react component if it is updated. It has the right to block updates. Try to follow the default behavior.

  • SetState cannot be called

  • Return false to not update;

  • This method can reduce unnecessary rendering of components and improve performance.

# # # # componentWillUpdate (nextProps nextState)

  • It is executed before an update occurs, and is rarely used. SetState cannot be called

componentDidUpdate(prevProps, prevState)

  • The update completes the call and gives you a chance to manipulate the DOM

  • Suitable for determining whether to send a network request

    Note: be sure to compare conditions, otherwise it may cause an endless loop

Unloading phase

componentWillUnmount

  • Called directly before component uninstallation and destruction, this method performs necessary cleanup actions, such as clearing timers, canceling network requests, or clearing subscriptions created in componentDidMount().
  • SetState () cannot be called because the component will never be re-rendered. Once a component instance is unmounted, it will never be mounted again.

Error handling phase

componentDidCatch(error, info)

This life cycle is invoked after a descendant component throws an error. It takes two arguments:

  1. Error: A thrown error
  2. Info: Object with componentStack key, which contains stack information about component raising errors

See the documentation for details

Controllable and non-controllable components

Controllable and uncontrolled components are used primarily for forms, and the core difference between them is whether the input value corresponds to the value of state

Controllable components

  • Controllable components depend on state. Default values map to state in real time.

  • The onChange event must be used to process the value, and the value cannot be changed otherwise.

  • Advantages:

    • React compliant data flow, one-way
    • Modify the use of more convenient, just need to modify the desired value, value will change, no need to obtain dom
    • Facilitate data processing
class Footer extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      username: "Controlled Component Defaults"}; } handleChange =(e) = > {
    this.setState({
      username: e.target.value,
    });
  };
  render() {
    return (
      <div>
        <input
          type="text"
          onChange={this.handleChange}
          value={this.state.username}
        />{/* Error without onChange -> Warning: You provided a "value" item for a form field without an onChange handler. This will render a read-only field. If the field is mutable, use 'defaultValue'. Otherwise, set 'onChange' or 'readOnly '*/}</div>); }}Copy the code

Non-controllable component

  • The state of data in the middle of uncontrollable components is unknown and can only be obtained from DOM nodes. However, when the value of controllable components changes, it will be synchronized to state at any time, and the change of state is always synchronized

  • A ref is used to retrieve a value from a DOM node when an uncontrollable component retrieves a value

  • Advantages:

    • Easy to combine with third-party components
function Component() {
  const inputRef = React.createRef();

  function handled() {
    console.log("Values of uncontrolled components", inputRef.current.value);
  }

  return (
    <div className="App">
      <button onClick={handled}>P tags</button>
      <div>
        <label htmlFor="name">The user name</label>
        <input
          id="name"
          type="text"
          defaultValue="Uncontrolled Defaults"
          ref={inputRef}
        />
      </div>
    </div>
  );
}
Copy the code

React events and This

Events in React

React event binding is a direct uninstall of JSX. It does not require the native JS addEventListener to bind events.

Event name composition: on+EventType, such as onClick, onChange, onBlur and other camel name;

Custom tags cannot be used events, can only be used in native tags;

In React, the default behavior cannot be blocked by using return false inside the event. It can only be explicitly called with e.preventDefault().

handleClick = (event) = > {
  // e.preventDefault() => yes | return false => no
  //
  // do something
};

// jsx
<button onClick={handleClick}>P tags</button>;
Copy the code

In the code, Events are encapsulated internally in React and provide API interfaces externally, without considering compatibility

Event listening for this

We all know that the reference to this depends on the execution context; Global function calls in strict mode, this is undefined, non-strict mode refers to the window of the global object; If it is called as a method, the caller points to the caller. When called as a constructor function, this points to the created instantiation object, and when called by Call, apply, this points to their first argument.

There are four ways to bind this

  1. To avoid potential performance issues from binding this to render, we can pre-bind this in Constructor.

    class App extends React.Component {
      constructor(props) {
        super(props);
        this.handleClick = this.handleClick.bind(this);
      }
      handleClick() {
        console.log("this > ".this);
      }
      render() {
        return <div onClick={this.handleClick.bind(this)}>test</div>; }}Copy the code
  2. Using bind in JSX (not recommended)

    class App extends React.Component {
      handleClick() {
        console.log("this > ".this);
      }
      render() {
        return <div onClick={this.handleClick.bind(this)}>test</div>; }}Copy the code

    This approach is simple, but since the component performs render due to changes in props, internal functions are recreated as well, which affects performance. Especially if you make some performance optimizations, it will break PureComponent performance.

  3. Using arrow functions (recommended)

    class App extends React.Component {
      handleClick = () = > {
        console.log("this > ".this);
      };
      render() {
        return <div onClick={this.handleClick.bind(this)}>test</div>; }}Copy the code

    This approach automatically binds to the scope of the current component, does not change by Call, and avoids the performance issues of binding within JSX and the need to write a lot of repetitive code in constructors.

  4. Arrow functions are used in JSX elements

    class App extends React.Component {
      handleClick = () = > {
        console.log("this > ".this);
      };
      render() {
        return <div onClick={()= > this.handleClick}>test</div>; }}Copy the code

    This method is also used in the render function and has performance issues, so it is not recommended

Event pass arguments

  1. The way parameters are passed

    • bind
    class Footer extends React.Component {
      handleBtnClick = (event, params) = > {
        console.log("I am the passed value of the parameter.", params);
      };
      render() {
        return (
          <div>
            <button onClick={this.handleBtnClick.bind(this,"Parameters passed123")} >Passing parameters</button>
          </div>); }}Copy the code
    • Arrow function
    class Footer extends React.Component {
      handleBtnClick = (params, event) = > {
        console.log("I am the passed value of the parameter.", params);
      };
      render() {
        return (
          <div>
            <button onClick={(e)= >This.handlebtnclick (e, "pass 456")}> pass the parameter</button>
          </div>); }}Copy the code