Front-end react tutorial (detailed version)

1. React overview

1.1 What is React

  • React is a JavaScript library for building user interfaces.
  • The main features of React are componentization, declarative programming, and an efficient DOM update mechanism.
  • React was developed and open sourced by Facebook, and has become one of the most popular front-end frameworks.

1.2 Features of React

  • Declarative programming : React adopts a declarative programming model, which makes the code easier to read and understand.
  • Componentization : React decomposes the page into multiple components, and each component has its own state and life cycle, which is convenient for reuse and maintenance.
  • One-way data flow : React adopts a one-way data flow mode. The parent component passes data to the child component through props, and the child component passes data to the parent component through the callback function.
  • Virtual DOM : React adopts the technology of virtual DOM. By comparing the difference between the two virtual DOMs before and after, it minimizes the redrawing and reflow of the page, and improves the performance and response speed of the page.
  • Efficiency : React uses efficient algorithms and mechanisms to render pages faster and provide better user experience.

1.3 Advantages of React

  • Better user experience : React uses virtual DOM, which can update pages faster and improve user experience.
  • Component-based development : React adopts component-based development, which makes the code more modular and reusable, and improves development efficiency.
  • High code maintainability : React adopts one-way data flow, which makes the data flow of the code clearly visible and convenient for maintenance and debugging.
  • Active community : React has a huge community and ecosystem, and can provide a wealth of plug-ins and components for easy development.

1.4 Disadvantages of React - Disadvantages of React:

  • The learning curve is relatively steep, requiring a certain JavaScript foundation and understanding of JSX syntax;
  • Only focus on the view layer, not other aspects, need to be used in conjunction with other libraries or frameworks;
  • The code complexity is high, and a large number of components and logic codes need to be written;
  • Browsers of IE8 and below versions are not supported, and polyfills are required for compatibility.

2. Basic knowledge of React

2.1 JSX syntax

- JSX syntax example:

const element = <h1>Hello, world!</h1>; // JSX语法
ReactDOM.render(element, document.getElementById('root')); // 渲染到页面

- JSX expression example:

function formatName(user) {
    
    
 return user.firstName + ' ' + user.lastName;
}

const user = {
    
    
 firstName: 'Tony',
 lastName: 'Stark'
};

const element = (
 <h1>
   Hello, {
    
    formatName(user)}!
 </h1>
);

ReactDOM.render(element, document.getElementById('root')); // 渲染到页面

- JSX attribute instance:

const element = <div tabIndex="0">Hello, world!</div>; // JSX属性
ReactDOM.render(element, document.getElementById('root')); // 渲染到页面

2.2 Components

- 2.2 Components

  • Example 1: Hello World component

    import React from 'react';
    
    function HelloWorld() {
          
          
      return <h1>Hello, World!</h1>;
    }
    
    export default HelloWorld;
    
  • Example 2: Counter component

    import React, {
          
           useState } from 'react';
    
    function Counter() {
          
          
     const [count, setCount] = useState(0);
    
     return (
       <div>
         <p>Count: {
          
          count}</p>
         <button onClick={
          
          () => setCount(count + 1)}>Increment</button>
         <button onClick={
          
          () => setCount(count - 1)}>Decrement</button>
       </div>
     );
    }
    
    export default Counter;
    
  • Example 3: Table Component

    import React from 'react';
    
    function Table(props) {
          
          
     const {
          
           data } = props;
    
     return (
       <table>
         <thead>
           <tr>
             <th>Name</th>
             <th>Age</th>
             <th>Gender</th>
           </tr>
         </thead>
         <tbody>
           {
          
          data.map((item) => (
             <tr key={
          
          item.id}>
               <td>{
          
          item.name}</td>
               <td>{
          
          item.age}</td>
               <td>{
          
          item.gender}</td>
             </tr>
           ))}
         </tbody>
       </table>
     );
    }
    
    export default Table;
    

2.2.1 Functional components

- Functional components

function Welcome(props) {
    
    
  return <h1>Hello, {
    
    props.name}</h1>;
}

ReactDOM.render(
  <Welcome name="John" />,
  document.getElementById('root')
);

2.2.2 Class components

  • Class components are a way to define components in React, using ES6 class syntax to declare components.
  • Class components must inherit the React.Component class and implement the render method to describe the UI of the component.
  • Class components can define their own state state, update the state and re-render the component through the setState method.
  • Class components can also define their own methods for handling user interaction or other logic.
  • Class components can receive props as input data, accessed through this.props.
  • The life cycle of a class component includes three phases of mounting, updating and unmounting, and some specific logic can be implemented by rewriting the life cycle method.

Example:

import React, {
    
     Component } from 'react';

class MyComponent extends Component {
    
    
 constructor(props) {
    
    
   super(props);
   this.state = {
    
    
     count: 0
   };
 }

 handleClick = () => {
    
    
   this.setState({
    
     count: this.state.count + 1 });
 }

 render() {
    
    
   return (
     <div>
       <h1>{
    
    this.props.title}</h1>
       <p>Count: {
    
    this.state.count}</p>
       <button onClick={
    
    this.handleClick}>Click me</button>
     </div>
   );
 }
}

export default MyComponent;

Form example:

properties/methods describe
state the component's state object
setState() Update the state of the component
props Component input properties
render() Ways to describe component UI
componentDidMount() The method called after the component is mounted
componentDidUpdate() The method called after the component is updated
componentWillUnmount() The method called before the component is unmounted

2.3 Props and State

  • The difference between Props and State:
point of difference Props State
Storage location Passed from parent component to child component Component internal initialization
Is it variable immutable, read-only variable, modifiable
Corresponding component type function components and class components Only class components
trigger view update The props passed by the parent component change The setState() method is called by the component itself
life cycle Does not affect component lifecycle Life cycles such as shouldComponentUpdate, componentWillUpdate, render, componentDidUpdate, etc. may be triggered

- Use of Props:

function ParentComponent() {
    
    
 const name = "小明";
 return (
   <ChildComponent name={
    
    name} />
 );
}

function ChildComponent(props) {
    
    
 return (
   <div>
     <p>我是子组件</p>
     <p>我的名字是:{
    
    props.name}</p>
   </div>
 );
}

- Use of State:

class Counter extends React.Component {
    
    
 constructor(props) {
    
    
   super(props);
   this.state = {
    
    
     count: 0
   };
 }

 handleClick = () => {
    
    
   this.setState({
    
    
     count: this.state.count + 1
   });
 }

 render() {
    
    
   return (
     <div>
       <p>当前计数:{
    
    this.state.count}</p>
       <button onClick={
    
    this.handleClick}>增加计数</button>
     </div>
   );
 }
}

2.4 Life cycle

  • The life cycle of React components includes: mount phase, update phase, and unmount phase.
  • The mount phase includes constructor, getDerivedStateFromProps, render, componentDidMount.
  • The update phase includes getDerivedStateFromProps, shouldComponentUpdate, render, getSnapshotBeforeUpdate, componentDidUpdate.
  • The unmount phase includes componentWillUnmount.

2.5 Event handling - The event handling in React is different from the native DOM event handling. It uses synthetic events (SyntheticEvent) to encapsulate the browser's native events, providing cross-browser consistency.

  • In React, event handlers need to be bound to component instances, either using arrow functions or using the bind method in the constructor.
  • The this in the event handler function defaults to the component instance, not the DOM element that triggered the event.
  • The parameter e of the event handler is a synthetic event object, which contains the same properties and methods as the original event, such as e.target, e.stopPropagation(), etc.
  • Event handlers in React cannot return false to prevent event bubbling, but need to use e.stopPropagation() or e.preventDefault() to achieve the same effect.
  • Sample code:
 class MyComponent extends React.Component {
    
    
   handleClick = (e) => {
    
    
     console.log('Button clicked!');
   }
 
   render() {
    
    
     return (
       <button onClick={
    
    this.handleClick}>Click me</button>
     );
   }
 }

Example of table syntax:

React event handling illustrate
onClick mouse click event
onDoubleClick mouse double click event
onMouseDown mouse down event
onMouseUp mouseup event
onKeyDown keyboard press event
onKeyUp keyboard release event
onFocus Element gets focus event
onBlur Element loses focus event

3. React advanced knowledge

3.1 Higher-order components

  • What are higher order components?
    • A higher-order component is a function that takes a component as an argument and returns a new component.
  • What is the role of higher-order components?
    • Higher-order components can help us achieve component reuse, logic abstraction and encapsulation, and enhance component functions without changing the original component.
  • What are the implementation methods of high-order components?
    • Property proxy: Enhance the functionality of components by wrapping the original components and passing new props to them.
    • Reverse Inheritance: Enhance the function of a component by inheriting the original component and rewriting its methods.
  • What are the application scenarios of high-order components?
    • Conditional Rendering: Render different components based on conditions.
    • Authentication and Authorization: Render different components based on the user's authentication status and permissions.
    • Data acquisition and processing: The logic of data acquisition and processing is separated from the components, making the components more concise and reusable.
    • Function enhancement: enhance the function of the component, such as adding logging, performance statistics, etc.
  • What are the precautions for high-order components?
    • Higher-order components should not modify the props and state of the original component.
    • High-level components should transparently transmit the props and context of the original component.
    • Higher-order components should follow the principles of functional programming and should not have side effects.

3.2 Hooks

  • useState
import React, {
    
     useState } from 'react';

function Example() {
    
    
  // 声明一个叫 "count" 的 state 变量
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {
    
    count} times</p>
      <button onClick={
    
    () => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}
  • useEffect
  import React, {
    
     useState, useEffect } from 'react';

  function Example() {
    
    
    const [count, setCount] = useState(0);

    // 相当于 componentDidMount 和 componentDidUpdate:
    useEffect(() => {
    
    
      // 使用浏览器的 API 更新页面标题
      document.title = `You clicked ${
      
      count} times`;
    });

    return (
      <div>
        <p>You clicked {
    
    count} times</p>
        <button onClick={
    
    () => setCount(count + 1)}>
          Click me
        </button>
      </div>
    );
  }
  • useContext
    import React, {
          
           useContext } from 'react';
    
    const ThemeContext = React.createContext('light');
    
    function App() {
          
          
      return (
        <ThemeContext.Provider value="dark">
          <Toolbar />
        </ThemeContext.Provider>
      );
    }
    
    function Toolbar(props) {
          
          
      return (
        <div>
          <ThemedButton />
        </div>
      );
    }
    
    function ThemedButton() {
          
          
      const theme = useContext(ThemeContext);
      return <button>{
          
          theme}</button>;
    }
    
  • useReducer
  import React, {
    
     useReducer } from 'react';

  const initialState = {
    
     count: 0 };

  function reducer(state, action) {
    
    
    switch (action.type) {
    
    
      case 'increment':
        return {
    
     count: state.count + 1 };
      case 'decrement':
        return {
    
     count: state.count - 1 };
      default:
        throw new Error();
    }
  }

  function Counter() {
    
    
    const [state, dispatch] = useReducer(reducer, initialState);
    return (
      <>
        Count: {
    
    state.count}
        <button onClick={
    
    () => dispatch({
    
     type: 'increment' })}>+</button>
        <button onClick={
    
    () => dispatch({
    
     type: 'decrement' })}>-</button>
      </>
    );
  }
  • useCallback
    import React, {
          
           useState, useCallback } from 'react';
    
    function Example() {
          
          
      const [count, setCount] = useState(0);
      const [text, setText] = useState('');
    
      const handleChange = useCallback(e => {
          
          
        setText(e.target.value);
      }, []);
    
      return (
        <div>
          <p>You clicked {
          
          count} times</p>
          <button onClick={
          
          () => setCount(count + 1)}>
            Click me
          </button>
          <input value={
          
          text} onChange={
          
          handleChange} />
        </div>
      );
    }
    
  • use Memo
  import React, {
    
     useState, useMemo } from 'react';

  function Example() {
    
    
    const [count, setCount] = useState(0);

    const expensiveCount = useMemo(() => {
    
    
      return count ** 2;
    }, [count]);

    return (
      <div>
        <p>You clicked {
    
    count} times</p>
        <p>Expensive count: {
    
    expensiveCount}</p>
        <button onClick={
    
    () => setCount(count + 1)}>
          Click me
        </button>
      </div>
    );
  }

3.2.1 useState

  • useState basic usage:
import React, {
    
     useState } from 'react';

function Example() {
    
    
  // 声明一个叫 "count" 的 state 变量
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {
    
    count} times</p>
      <button onClick={
    
    () => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}
  • useState uses a function to update the state:
 import React, {
    
     useState } from 'react';

 function Example() {
    
    
   const [count, setCount] = useState(0);

   function handleClick() {
    
    
     setCount(prevCount => prevCount + 1);
   }

   return (
     <div>
       <p>You clicked {
    
    count} times</p>
       <button onClick={
    
    handleClick}>
         Click me
       </button>
     </div>
   );
 }
  • useState can accept a function as an initial value:

    import React, {
          
           useState } from 'react';
    
    function Example() {
          
          
    const [count, setCount] = useState(() => {
          
          
      const initialCount = 0;
      return initialCount;
    });
    
    return (
      <div>
        <p>You clicked {
          
          count} times</p>
        <button onClick={
          
          () => setCount(count + 1)}>
          Click me
        </button>
      </div>
    );
    }
    
  • useState can use destructuring assignment:

    import React, {
          
           useState } from 'react';
    
    function Example() {
          
          
     const [state, setState] = useState({
          
           count: 0, name: '张三' });
    
     function handleClick() {
          
          
       setState(prevState => {
          
          
         return {
          
           ...prevState, count: prevState.count + 1 };
       });
     }
    
     return (
       <div>
         <p>{
          
          state.name} clicked {
          
          state.count} times</p>
         <button onClick={
          
          handleClick}>
           Click me
         </button>
       </div>
     );
    }
    

3.2.2 useEffect

  • useEffect is a Hook in React, which is used to handle side-effect operations in components, such as data acquisition, DOM operations, etc.

  • The basic usage of useEffect is as follows:

    import React, {
          
           useEffect } from 'react';
    
    function Example() {
          
          
      useEffect(() => {
          
          
        // 在这里处理副作用操作
        return () => {
          
          
          // 在组件卸载时执行清除操作
        };
      }, [/* 依赖项 */]);
    
      return <div>Example</div>;
    }
    
  • useEffect receives two parameters, the first parameter is a callback function, used to handle side effects; the second parameter is an array, used to specify the dependencies of the side effects operation, only when the dependencies change, the side effects will be re-executed operate.

  • useEffect can also return a cleanup function to perform cleanup when the component is unmounted.

3.2.3 useContext

  • Use useContext for inter-component communication
 import React, {
    
     useContext } from 'react';

 // 创建一个context
 const MyContext = React.createContext();

 // 在父组件中设置context的值
 function Parent() {
    
    
   return (
     <MyContext.Provider value="hello">
       <Child />
     </MyContext.Provider>
   );
 }

 // 在子组件中使用context的值
 function Child() {
    
    
   const value = useContext(MyContext);
   return <div>{
    
    value}</div>;
 }

3.3 Redux

  • Redux is a state management tool that helps us better manage data flow in React.
  • Redux has three core concepts: store, action, and reducer.
  • The store is where data is saved in Redux, and we can get the data in the store through store.getState().
  • Action is an object describing an event in Redux, and it must contain a type attribute to describe the type of event.
  • reducer is a function that handles events in Redux, it receives the current state and action, and returns a new state.
  • The use of Redux requires the installation of two packages, redux and react-redux, and the creation of a store in the application.
  • When using Redux, we need to define actions and reducers and register them in the store.
  • You can use redux-devtools to easily debug Redux applications.
  • Redux can also be used in conjunction with React to map the state of Redux to the props of React components through the connect function provided by react-redux.
  • When using Redux, you need to be careful not to abuse Redux, use it only when you need to manage a lot of shared state, otherwise the code will become complicated and difficult to maintain.

3.4 React Router - What is React Router?

  • React Router is a powerful routing library based on React that allows you to add routing functionality to your application so that users can access different pages through URLs.
  • How to use React Router
    • Install React Router:npm install react-router-dom
    • Introduce React Router in the application:import { BrowserRouter as Router, Route, Link } from "react-router-dom";
    • Use <Router>components to wrap the entire application, use <Route>components to define routing rules, and use <Link>components to generate links.
  • Common APIs of React Router
    • <Route>Component: Defines routing rules, contains pathand componenttwo properties.
    • <Link>Component: generate link, contains toattributes.
    • useHistoryHook: Obtain routing history, which can be used to realize page jump.
  • Advanced usage of React Router
    • Nested routing: Nest a routing rule within another routing rule.
    • Dynamic Routing: Use parameters to define routing rules, eg /users/:id.
    • Routing Guard: Perform permission verification or other operations before routing jumps. This can be achieved using <Route>component renderproperties or custom components.

4. React in practice

4.1 Create a React application

  • Create a React application with create-react-app
  • Add components to the application and render
  • Pass data to components using props
  • Use state to manage internal state of components
  • Handle component events
  • Controlling Component Behavior Using Lifecycle Methods
  • Implement page routing with React Router
  • Manage application state with Redux
  • Optimizing component code with React Hooks
  • Unit testing with React testing tools
  • Developing Mobile Apps with React Native
  • Server rendering with Next.js
  • Use React to integrate with other technology stacks, such as GraphQL, TypeScript, etc.
  • Experience sharing of using React to develop actual projects
  • Summary and Outlook

Form syntax:

serial number content
1 Create a React application with create-react-app
2 Add components to the application and render
3 Pass data to components using props
4 Use state to manage internal state of components
5 Handle component events
6 Controlling Component Behavior Using Lifecycle Methods
7 Implement page routing with React Router
8 Manage application state with Redux
9 Optimizing component code with React Hooks
10 Unit testing with React testing tools
11 Developing Mobile Apps with React Native
12 Server rendering with Next.js
13 Use React to integrate with other technology stacks, such as GraphQL, TypeScript, etc.
14 Experience sharing of using React to develop actual projects
15 Summary and Outlook

4.2 Integration of React with other frameworks

  • React and Vue.js integration

    Sample code:

    // 在Vue.js组件中使用React组件
    <template>
      <div>
        <my-react-component :prop1="value1" @event1="handleEvent"></my-react-component>
      </div>
    </template>
    
    <script>
      import MyReactComponent from './MyReactComponent';
    
      export default {
          
          
        components: {
          
          
          'my-react-component': MyReactComponent
        },
        data() {
          
          
          return {
          
          
            value1: 'some value'
          }
        },
        methods: {
          
          
          handleEvent() {
          
          
            // 处理React组件触发的事件
          }
        }
      }
    </script>
    
  • React and Angular integration

    Sample code:

    // 在Angular组件中使用React组件
    import {
          
           Component, ElementRef, Input, OnInit, ViewChild } from '@angular/core';
    import * as React from 'react';
    import * as ReactDOM from 'react-dom';
    import {
          
           MyReactComponent } from './MyReactComponent';
    
    @Component({
          
          
      selector: 'app-my-angular-component',
      template: '<div #reactContainer></div>',
    })
    export class MyAngularComponent implements OnInit {
          
          
      @ViewChild('reactContainer', {
          
           static: true }) reactContainer: ElementRef;
    
      @Input() prop1: string;
    
      ngOnInit() {
          
          
        ReactDOM.render(<MyReactComponent prop1={
          
          this.prop1} />, this.reactContainer.nativeElement);
      }
    }
    
  • React and jQuery integration

    Sample code:

    // 在jQuery插件中使用React组件
    (function($) {
          
          
      $.fn.myJqueryPlugin = function(options) {
          
          
        const settings = $.extend({
          
          }, options);
    
        return this.each(function() {
          
          
          const $this = $(this);
          const props = {
          
           prop1: settings.prop1 };
    
          ReactDOM.render(<MyReactComponent {
          
          ...props} />, $this[0]);
        });
      };
    })(jQuery);
    

4.3 React performance optimization

4.4 React Testing - Component Testing with Jest and Enzyme

  • Component testing with React Testing Library
  • End-to-end testing with Cypress
  • Unit testing with Sinon
  • Integration testing with Mocha and Chai
  • Full-stack testing with Jasmine
  • sheet:
test framework advantage shortcoming
Is Fast, easy to use, supports snapshot testing High integration, not easy to customize
Enzyme Support shallow rendering and deep rendering, easy to test component life cycle Does not support the new features of React16
React Testing Library It is more in line with user behavior and the test is more realistic It is not easy to test the internal state of components
Cypress Can perform end-to-end testing and support debugging Can't test multiple browsers
Otherwise Functions and objects can be mocked, making it easy to test asynchronous code Need to work with other testing frameworks
Mocha和Chai Flexible, easy to use, and can be integrated with other testing frameworks Requires manual installation and configuration
Jasmine Full-stack testing is possible, making it easy to test asynchronous code The integration level is not high, and it is not easy to customize

5. References

5.1 React Official Documentation

  • React official documentation: https://reactjs.org/docs/getting-started.html

    React官方文档是React框架的官方文档,提供了详细的React介绍、快速上手指南、组件API等内容,是学习React的必备资料。在这里,你可以了解到React的基本概念、核心特性、组件生命周期、事件处理等知识点,并且可以通过实例代码进行实践操作,加深对React的理解。同时,React官方文档也提供了React Native、React VR等相关技术的文档,方便开发者进行深入学习和应用。

5.2 React源码解析

  • React源码解析官方文档:https://reactjs.org/docs/codebase-overview.html
  • React源码解析系列博客:https://react.iamkasong.com/
  • React源码解析视频教程:https://www.bilibili.com/video/BV1qE411b7cZ
  • React源码解析Github仓库:https://github.com/facebook/react
  • 表格:React源码解析书籍推荐
书名 作者 出版社 链接
《React源码解析》 陈屹著 机械工业出版社 https://book.douban.com/subject/30374649/

5.3 React实战教程- React官方文档:https://reactjs.org/docs/getting-started.html

  • React中文文档:https://zh-hans.reactjs.org/
  • 5.3 React实战教程:
    • React小书:http://huziketang.mangojuice.top/books/react/
    • React Native官方文档:https://reactnative.dev/docs/getting-started
    • React Router官方文档:https://reactrouter.com/web/guides/quick-start
    • Ant Design官方文档:https://ant.design/docs/react/introduce-cn
    • Material-UI官方文档:https://material-ui.com/zh/getting-started/installation/
    • Redux官方文档:https://redux.js.org/introduction/getting-started
    • Mobx官方文档:https://mobx.js.org/README.html
    • TypeScript官方文档:https://www.tslang.cn/docs/home.html
    • Next.js官方文档:https://nextjs.org/docs/getting-started
    • Gatsby官方文档:https://www.gatsbyjs.com/docs/

Guess you like

Origin blog.csdn.net/it_varlue/article/details/129951140
Recommended