This article has participated in the “Digitalstar Project” and won a creative gift package to challenge the creative incentive money.

โœ‰ ๏ธ preface

On the surface of React, we probably hear a lot about declarative development, one-way data flow, componentized development, and so on. React props, virtual DOM, REF, transition animation, etc.

In the following article, we’ll explore more advanced knowledge about React.

Ding, below begins the introduction of this article ~๐Ÿคช

๐Ÿ“งไธ€ใ€props

PropTypes and DefaultProps application

(1) PropTypes

In React, propTypes are used when we need to format an attribute in a component. Here are some common examples:

TodoItem = TodoItem; // TodoItem = TodoItem
TodoItem.propTypes = {
    // isRequired: there must be a value
    test: PropTypes.string.isRequired,
    // The propTypes for content must be string, so the string check is taken from the propTypes package
    content: PropTypes.string,
    // The detail can be a number or a string
    detail: PropTypes.arrayOf(PropTypes.number, PropTypes.string),
    // deleteItem must be a function
    deleteItem: PropTypes.func,
    // indicates that index must be a numeric type
    index: PropTypes.number
}
Copy the code

(2) defaultProps

Sometimes, if we want to give an initial value for an attribute, we need defaultProps. The following is an example:

TodoItem.defaultProps = {
    test: 'hello world'
}
Copy the code

The code above shows that when the test property is not assigned, it will be given an initial value of Hello World.

Props, state, and render functions

In React, when defining a component, you often see props, state, and Render. What is the relationship between them?

The first question we need to ask is: why do pages change when data changes?

The reason is that the page is rendered by the render function, which is re-executed when the data state changes.

Also, when the parent component’s render function is run, its child component’s Render is rerun.

๐Ÿ“จ React virtual DOM

What is the virtual DOM

(1) The first scheme

The traditional idea of virtual DOM is as follows:

  • To define thestateThat is, data;
  • writeJSXTemplate content;
  • theData and TemplatesCombine to produce realDOMTo display the content on the page;
  • If data is to be replaced, theData and TemplatesCombine to produce the realDOMTo replace the originalDOM ใ€‚

Defects:

  • For the first time, a completeDOMFragments;
  • And then the second time it generates a complete oneDOMFragments;
  • The secondDOMReplace the first oneDOM, very performance consuming.

(2) The second scheme

An improved version of the traditional implementation of virtual DOM:

  • To define thestate, data;
  • writeJSXTemplate content;
  • theData and TemplatesCombine to produce the realDOM, and display;
  • whenstateChanges in data;
  • To continue,Data and TemplatesCombine to produce the realDOMIt’s not directly replacing the originalDOM
  • Will the newDOMAnd the originalDOMFor comparison,And find the differences;
  • Find a newDomThe changes that have taken place in;
  • onlynewtheDOM ไธญChanging dataTo replace itThe oldtheDOMData in.

Defects:

  • The performance improvement is not significant

(3) The third scheme

React virtual DOM

  • Define state, or data;

  • Write JSX template content;

  • Combine data with templates to generate a virtual DOM (which is a JS object that describes the real DOM). ๐Ÿ‘‰ (loss of performance)

    <div id="abc"><span>hello world</span></div>
    ['div', {id: 'abc'},'span', {}, 'hello world']]
    Copy the code
  • The structure of virtual DOM is used to generate real DOM for display.

  • When state changes, the data + template generates a new virtual DOM. ๐Ÿ‘‰ (greatly improved performance)

<div id="abc"><span>monday</span></div> 
['div', {id: 'abc'},'span', {}, 'monday']]
Copy the code
  • To compareThe original virtualDOM ๅ’Œ The new virtualDOMFind the difference betweenspanThe contents of;
  • Direct manipulationDOMChange,spanThe content of the;
  • As a result,ReactThe virtualDOMThe main process is:JSX โ†’ createElement– > virtualDOM ๏ผˆ JSObject) โ†’ realDOM ใ€‚

React virtual DOM benefits:

  • Greatly improved performance;
  • It makes theAcross the end applicationTo be realized, that’s going to be talked aboutreactIs a concept of,react native ๏ผ›
  • reactUse can write native applications likeAndroid ๅ’Œ IOSDevelopment, these are operational realityDOM ๏ผ›
  • whilereactMake it possible to writeNative applicationsBe used.

2. Diff algorithm in virtual DOM

  • react ๅฏน setStateThe performance optimization, it will put multiple timessetStateCombine into onesetState ๏ผ›
  • virtualDOMusediffAlgorithms to compare,Only compare at the same level, not across levels;
  • The algorithm of the same layer comparison is relatively simple, and the direct benefit of the simplicity of the algorithm is very fast;
  • Although it may causeDOMThere is some waste in rendering, but it also greatly reduces both virtualizationsDOMThe cost of performance when compared between.

๐Ÿ“ฉ use of ref in React

React suggests that we write code in a data-driven format and try not to manipulate the DOM. But sometimes, when we’re doing something extremely complex, such as a variety of shock animations, it’s inevitable to use some native DOM tags. Therefore, ref helps us use it when react directly fetches DOM elements.

In general, we try not to use refs. If you use ref, you get all kinds of problems. Also, be aware of some pits when using ref and setState.

For example, when ref is used in conjunction with setState, note that setState is an asynchronous function and tends to execute asynchronous code after synchronous code has finished executing. Therefore, if we want to synchronize code after setState, we can add a callback function to the second argument accepted by setState.

render() {
    return (
        <ul ref={(ul)= > this.ul = ul}>
        	{this.getTodoItem()}
        </ul>)}this.setState((prevState) = > ({
    list: [...prevState.list, prevState.inputValue],
    inputValue: ' '
}), () = > {
    console.log(this.ul.querySelectorAll('div').length)
});
Copy the code

๐Ÿ“ฆ 4. Life cycle in React

1. What is the lifecycle function

A lifecycle function is a function that is automatically invoked by a component at some point. What are the react life cycles?

phase The life cycle meaning
Mounting componentWillMount (1) Automatically execute when the component is about to be mounted to the page, that is, execute before the page is mounted; (2) Execute only when the component is first mounted on the page;
Mounting/Updation render Executed when the page is mounted
Mounting componentDidMount Is executed automatically after the component is mounted to the page. Execution occurs only when the component is first hung on the page
Updation componentWillReceiveProps (1) When a component receives arguments from its parent; โ‘ก As long as the parent componentrenderWhen the function is executed, the child component’s lifecycle function is executed; If the component first exists in the parent component, it will not be executed. (4) The component is executed only if it already exists in the parent component.
Updation componentWillUpdate (1) Before the component is updated, it will automatically execute; โ‘ก But it is inshouldComponentUpdateAnd then it’s executed ifshouldComponentUpdatereturntrue“, it is executed; If the returnfalse, the function will not be executed.
Updation componentDidUpdate After the component update is complete, it will be executed.
Updation shouldComponentUpdate Before a component is updated, it is automatically executed; This life cycle returns oneBoolean value
Unmounting componentWillUnmount Is executed when the component is about to be removed from the page.

2. Legend of life cycle

Here’s a diagram to show how life cycles are executed in React:

๐Ÿ“ช use CSS animations in React

1. Common usage

Let’s take a look at how cSS3 provides animations in React. The specific code is as follows:

.show {
  animation: show-item 2s ease-in forwards;
}

.hide {
  animation: hide-item 2s wase-in forwards;
}

@keyframes show-item {
  0% {
    oppacity: 0;
    color: red;
  }

  50% {
    opacity: 0.5;
    color: green;
  }

  100% {
    opacity: 1;
    color: blue; }}Copy the code

2, the react – the transition – group

(1) Initial exploration

Sometimes, we might want to implement some very complex animations, and cSS3 is not enough. Therefore, we also need a bit of JS to help achieve more complex animations. React: React-transition-group

Suppose we want to implement a line of text that fades out when a button is clicked, what do we do?

First, we’ll add a new component in the project’s SRC folder named app.js. The specific code is as follows:

import React, { Component, Fragment } from 'react';
import { CSSTransition } from 'react-transition-group';
import './style.css';

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      show: true
    }
    this.handleToggle = this.handleToggle.bind(this);
  }

  render() {
    return (
      <Fragment>{/* onEntered refers to a function that is automatically executed at some point when the entry animation ends.<CSSTransition
          in={this.state.show}
          timeout={1000}
          classNames='fade'
          unmountOnExit
          onEntered={(el)= > { el.style.color = "blue" }}
          appear={true}
        >
          <div>hello</div>
        </CSSTransition>
        <button onClick={this.handleToggle}>toggle</button>
      </Fragment>)}handleToggle() {
    this.setState({
      show: this.state.show ? false : true}}})export default App;
Copy the code

Add a new CSS file named style.css. The specific code is as follows:

/* The first moment of the entry animation execution, i.e. the moment of entry */
/* fade-appear */
.fade-enter..fade-appear {
  opacity: 0;
}

/* The second moment of the entry animation execution, until the moment before the entry animation execution is complete */
.fade-enter-active..fade-appear-active {
  opacity: 1;
  transition: opacity 1s ease-in;
}

/* When the entire entry animation is executed */
.fade-enter-done {
  opacity: 1;
}

/* represents the first time the appearance animation is executed */
.fade-exit {
  opacity: 1;
}

/* The whole process */
.fade-exit-active {
  opacity: 0;
  transition: opacity 1s ease-in;
}

/* When the entire entry animation is completed */
.fade-exit-done{}Copy the code

Now let’s take a look at the browser display:

(2) Advanced exploration

We’ve just changed one statistic. Now, what if we want to add a transition effect when we click on it?

Let’s change the code of the app.js file. The specific code is as follows:

import React, { Component, Fragment } from 'react';
import { CSSTransition, TransitionGroup } from 'react-transition-group';
import './style.css';

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      show: true.list: []}this.handleToggle = this.handleToggle.bind(this);
  }

  render() {
    return (
      <Fragment>{/* onEntered refers to a function that is automatically executed at some point when the entry animation ends.<TransitionGroup>
          {
            this.state.list.map((item, index) => {
              return (
                <CSSTransition
                  in={this.state.show}
                  timeout={1000}
                  classNames='fade'
                  unmountOnExit
                  onEntered={(el)= > { el.style.color = "blue" }}
                  appear={true}
                  key={index}
                >
                  <div>{item}</div>
                </CSSTransition>)})}</TransitionGroup>
        <button onClick={this.handleToggle}>toggle</button>
      </Fragment>)}handleToggle() {
    this.setState((prevState) = > {
      return {
        list: [...prevState.list, 'item']}})}}export default App;
Copy the code

The browser runs as follows:

For this type of animation, we wrap the outer layer through TransitionGroup and then wrap the inner layer through CSSTransition to achieve our final effect.

๐Ÿ“ฎ 6. Conclusion

In this article, we looked at props in React and briefly looked at the virtual DOM. In addition, I also learned how to use ref and react’s cool transition animation. The most important thing, of course, is the life cycle function in React.

So that’s the end of react advancements. Do you have any further understanding of React?

๐Ÿ—ณ ๏ธ eggs

  • Pay attention to the public account Monday laboratory, the first time to pay attention to quality articles, more interview column for you to unlock ~
  • If you think this article is helpful to you, you might as well like to support yo ~~๐Ÿ˜‰
  • That’s all for this article! See you next time! ๐Ÿฅ‚ ๐Ÿฅ‚ ๐Ÿฅ‚