preface

React is a declarative javascript library for building user interfaces.

features

  • Ponent componentization React.Com
	class ShoppingList exteds React.Component {
    render() {
    // JSX syntax (lightweight description of rendered content) React element js objects, which can be used for parameter passing or variables using === react.createElement (); ReactDOM.render(jsx,dom)
    	return (
        	//xxx
            //{this.props.xxx}
            //onClick={function() {
            	xxx
            }
        ) 
    
    }
    }
Copy the code
  • The props property was passed
  • Interactive onClick
  • State of the state
Constructor to initialize stateconstructor(props) {
    	super(props);
        this.state = {
        	// Private attributes}} Change statethis.setState({/ /});
Copy the code
  • State of ascension

The state in the self-organizing price is promoted to the common parent component for saving, and the state data of the component is shared. A child component that does not hold state receives the value from the parent and notifies the parent to update state is called a controlled component.

  • On [Event], handle[Event]
  • immutability

Do not directly modify or change the underlying data, simplify complex functions.

Tracking data changes, directly modifying the data can make tracking data changes very difficult. shouldComponentUpdate

Creating a Pure component makes it immutable when properties change and components are rendered.

  • Functional component

Only render, no state

	function Square(props) {
    	return (
        	//
        );
    }
Copy the code
  • Practice the demo

Tic-tac-toe, time travel

  • React elements are first-class javascript objects in javascript.
  • When dynamically updating a list, specify an appropriate key that is unique in the current element of the same level.
  • Cannot be obtained by this.props. Key

jsx

Tags and components are placed in the build

Separation of concerns

1. Use a string to identify the string literal propName="propValue" 2. Babel will convert JSX to a react.createElement () function call {type:xx, props: { xx:xx } } 4. Element is the minimum brick structure react application Will react render elements to the root node in the DOM. Use ReactDOM render (element, the document getELementById (" root ")) 5. The react element is immutable objects Only the actual changes will be updatedCopy the code

Components and Properties

Standalone reusable snippets of code

Function components and class components

	function Xxx(props) {
    	return xxx;
    }
    // is essentially a javascript function
    
    // Es6 class defines the component
    class Xxx extends React.Component {
    	render() {
        	retuern xxx;
        }
    }
    <Xxx /> // Start with a capital letter
Copy the code

Combination of components

function APP (props) { return (

Break up the component

Break it down into smaller groups

Props is read-only and cannot change its own properties

React components are like pure functions and cannot change props

State and life cycle

State is a component’s private property

SetState ((state,props) => ({xx:state.xx + props}));

componentDidMount

Component mounted

componentWillUnmount

Component uninstall

Data is a one-way waterfall flowing downward

The event processing

  • The name is little Hump
  • {this.fn}
  • Displays a call to e.preventDefault() to block the default behavior
  • Bind this this.fn = this.fn.bind(this)
	1.
	fn = () = > {
    	//xxx
    }
	{this.fn}
    2.
    fn() {
    	//
    }
    {() = > this.fn()}
    3.The ginseng {(e) = > this.fn(xx,e)}
    {this.fn.bind(this,xx)}
Copy the code

Conditions apply colours to a drawing

  • Render different content if in the corresponding state according to the state of the application
  • Use element variables to store elements
  • The and operator &&

Use implementation conditional rendering in {}

  • Conditional rendering using the ternary operator
  • Preventing component rendering

The Render method returns NULL without affecting the life cycle of the component


List and key

The react key is used to tell the React component which elements have changed the key


The form

The controlled components

  • Maintain your own state
	input textarea select
Copy the code
  • form
	onSubmit
    onchange
Copy the code

State of ascension

Promote the state of a shared that reflects the same change to the nearest common parent


Combination and inheritance

Reuse of code using composition is recommended

Use {props. Children} to pass the child component to the render result

{props. Left} left= {} uses props to pass a concept similar to “slot”

Props can accept any type


React design philosophy

  • component
  • A single function
  • Implement a static version first, without too much interaction
  • Minimum representation of UI state (complete),
  • Determine where state is placed
  • Add a reverse data flow

barrier-free

aria-*

Semantic HTML

</ / XXX </ / XXX </>Copy the code

Accessible forms

	htmlFor
Copy the code

Control the focus

React.createref () uses the ref control component to forward refs to child components using the forwardRefCopy the code

The code segment

  • packaging
Importing and merging files into a single file forms a bundleCopy the code
  • Create multiple packages that are loaded dynamically at run time
Using dynamicimport 
import(xx).thne(xx= > {
	//xx
})
babel-plugin-sync-dynamic-import
Copy the code
  • Lazy loading
	React.lazy(() = > import())
    <Suspense fallback={xx}></Suspense>
Copy the code
  • Error boundary
  • Code segmentation based on routing
	1.Use the react - the router - the domCopy the code

context

Without adding props, implement component tree direct data transfer application shared global data

const ThemeContext =  React.creatContext('xxx')
<ThemeContext.provider value="xxx"></ThemeContext.provider> /ContextType = ThemeContext this.context; /provider; /provider; /provider; /provider; Pass the entire component that uses the data as props. Reduce the number of props passed. If you pass multiple components, pass multiple properties, something like slots. 
      
       { value => xx }</
      Themecontext. consumer> use displayName to set the name displayed in devTool * Use multiple contexts < themecontext1.consumer >{value1= >(< ThemeContext2. Consumer > {value2= >// Where values are used)} < / ThemeContext2. Consumer >)} < / ThemeContext1 consumer >Copy the code

Error boundary component

Avoid js errors in part of the UI causing the entire application to crash

Catch errors that occur during the construction render life cycle, using alternate components

	1.Catch error messagecomponentDidCatch(error) {
    	//
    }
    2.Render the wrong componentstatic gerDerivedStateFromError() {
    	return {} / / update the state
    }
Copy the code

Forwarding using REF

	1.Create a refconst ref = React.createRef()
    2.Custom Componentsconst Xxx = React.forwardRef((props,ref) = > (
    	<div ref={ref}></div>
        { props.children }
    ))
    3.Gets the DOM element ref.current to which ref pointsCopy the code

Forwarding refs in higher-order components

Properties can be passed transparently through the ref or the key can not pass through the forwardRef to the specified componentCopy the code

Using the fragments

	<React.Fragment>
    	// You don't need the parent tag</ react. Fragment> or <></> Pass the key when circulatingCopy the code

High order Component (HOC)

The argument is the component, and the return value is the function of the component

Use composition to avoid directly modifying the component's prototype as a container's component patternfunction xx(WrapperComponent) {
    	return class extends React.Component {
        	conponentDidMount(){}render() {
            	return (
                	<WrapperComponent {. this.props} >
                    	
                    </WrapperComponent>)}}}// Copy the static methods of the original component onto the new component
    
Copy the code

Use with third-party libraries

React generally maintains ITS own DOM updates. If a third party updates the same DOM, problems may occur. Avoid conflicts by disabling updates to componentsCopy the code

Delve into the advanced uses of JSX

	<Xxx.Xx>
    <xx[xx]> Assign the entire props {... This. Props} sets up to pass only partial properties {xx,... Other} = JSX content between the props start and end tags can be passed to the outer component {} for the JS expression {true && via props. Children<Xxx/> }
    
Copy the code

Performance optimization

Reduce dom manipulation

Use production versions for deployment

ShouldComponentUpdate When the props or state changes, The diff algorithm uses react. PureComponent to implement shallow comparisons of properties and states instead of handling shouldComponentUpdate without changing the original datathis.setState(state= >({xx: state.xx.concat(['xx'])}))Object.assign({},xx,{xx:xx})
    
Copy the code

portal

Render the child node into a node other than the parent component

The React. CreatePortal (child, container)Copy the code

Profiler

Can be used to measure the frequency of rendering and the time overhead used for rendering

Identify parts of the rendering that are slow

<Profiler id="xxx" onRender={callback}> </Profiler>
Copy the code

Several ways to create the React component

	1. function Xxx(props) {
    	return (
        	//)}2.class Xxx extends React.Component {
    	constructor(props) {
        	super(props)
            this.state = {
            	xx:xx
            }
            // Es6 methods need to bind this
            this.xx = this.xx.bind(this)}render() {
        	return (
            	xxx
            )
        }
    }
    
    // The first two implementations are ways to set the default props
    Xxx.defaultProps = {
    	xx:xx
    }
    
    3.Install create-react- without using ES6classThe plug-increateReactClass({
    	render: function() {
        	return xxx
        }
        // How to set the default properties
        getDefaultProps: function() {
        	return {
            	xx:xx
            }
        }
        
       // Initialize state
       getInitialState: function() {
       		return {
            	xx:xx
            }
       }
       
       // Methods are automatically bound to this, no binding required
       
    })
Copy the code

Use mixins

Same functionality, lifecycle methodmixins: [xx] // Set timer and clear timer
    
Copy the code

Diffing algorithm

The complexity of O (n ^ 3)

	1.If the root node type is different, remove the original tree and rebuild the tree2.When the elements are the same, compare the attributes of the elements and update the changed attributes3.Child component node4.The child nodes recurseCopy the code

Refs and dom

	1.Focus text selection2.Trigger forced animation3.Use a third party DOM library for HTML elementsclassUse on componentsrefThe function component cannot be usedrefThe callbackref
    ref= {el= > this.xx = el}
    
Copy the code

Render properties Render props

	<Xxx render={data= > (
    // Returns a custom render function
    // Do not render itself
    // Tell the component what to render}></Xxx> Render part of the component using the callback function {this.props.render(this.state) }
    
    children={ data= > (
      //)}Copy the code

Static type checking

Detect errors or bug messages at compile time1.Install NPX create-react-app xx --template typescript2.configurationsctript: {
        	"buid":"tsc"
        }
    3.NPX TSC --init generates tsconfig.json {"compilerOptions": {
        	"rootDir": xx,
            "outDir": xxx
        }
    }
    
    4.The compiler relies on declaring file type declarations declarations declarations declarations declarations declarations declarations declarations declarationsCopy the code

Strict mode

<React.StrictMode> // enable StrictMode </React.StrictMode> 1 Identify unsafe declaration cycle methods 2. Outdated API 3. Incorrect findDom method react Submit componentDidMount componentDidUpdate; 2. Render // Disassemble the render into multiple parts using concurrent mode for non-blocking renderingCopy the code

React built-in type checking for propType

Declare the component's propsType, xxx.propType = {"xx": PropType array | bool | object | number | element. IsRequired} to set the default properties of XXx. DefaultProps = {xx:xx
    }
Copy the code

Use uncontrolled components

Normally form submission uses a controlled component, which gives control to the React component,

Uncontrolled components give control to dom nodes


webComponent

The React component is a declarative solution that allows users to customize components

WebComponent components are embedded components that can be used as tags


	1.The React component uses webComponentrender() {
    	retutn (
        	<x-search class="xx">
            	
            </x-search>)}2.The React component is used in the webComponentclass Xxx extends HTMLElement {
    	connectedCallback() {
        	/ / create the dom
            // Place the created reactDom in the DOM
            ReactDom.render()
        }
    }
    
Copy the code

Core API explanation


	1.React entry for the top-level object2.ReactDOMServer renders components as static tagsCopy the code

Hook feature

Function components can implement state-like functionality without state


	import { useState } from 'react' // Hooks to state or lifecycle functions
    const [xx,setXxx] = useState(0);// Initialize the used state value and the method to change the state value
    
    // Similar to the use of state but more flexible data format
    
    
Copy the code

EffectHook

Added additional capability component mount update

	import { useEffect } from 'react';
    
    useEffect(() = > {
    	// componentDidMount componentDidUpdate
        // Call props state once for the first and after each render}) hook usage rules:1.Outermost function is used2.Used in the React function componentCopy the code

Customize the hook