React Event mechanism

Events written on JSX are not bound to the corresponding real DOM, but all events are uniformly bound to the Document through the way of event proxy. This approach not only reduces memory consumption, but also provides uniform subscription and removal of events when a component is mounted and destroyed.

The events that bubble up to the document are not native browser events, but synthetic events implemented by React itself. So event.stopPropagation is invalid if we don’t want the event to bubble, event.preventDefault should be called instead

The purpose of implementing a composite event is as follows:

  • Compositing events smoothes compatibility issues between browsers, and is a cross-browser native event wrapper that enables cross-browser development.
  • For native browser events, the browser creates an event object for the listener. If you have a lot of event listeners, then you need to allocate a lot of event objects, causing high memory allocation problems. For synthetic events, however, there is an event pool that manages their creation and destruction. When an event needs to be used, objects are reused from the pool, and after the event callback completes, the properties on the event object are destroyed so that the event object can be reused next time

How are React events different from normal HTML events

The difference between:

  • For event names, native events are all lowercase and React events have a small hump.
  • For event function handling syntax, native events are strings and React events are functions.
  • The React event cannot return false to block the browser’s default behavior, but must be explicitly calledpreventDefault()To prevent default behavior

React is an event object that simulates all the capabilities of native DOM events, with the following advantages:

  • Compatible with all browsers, better cross-platform;
  • Store events in an array to avoid frequent additions and deletions (garbage collection).
  • The React unified management and transaction mechanism is convenient.

The execution sequence of events is native event first and composite event later. The composite event will bubble and bind to document, so avoid mixing native event and composite event as much as possible. If the native event prevents bubbling, the composite event may not be executed, because it needs to bubble to document before the composite event is executed

How to do event proxy in React component? How does it work?

React implements a SyntheticEvent layer based on the Virtual DOM. The event handler receives an instance of a synthesized event object, which complies with W3C standards and has the same interface as native browser events. It supports the bubble mechanism, and all events are automatically bound to the uppermost layer.

The React layer does two things for compositing events:

  • Event delegate: React binds all events to the outermost layer of the structure, using a unified event listener that maintains a mapping to all component internal event listeners and handlers.
  • Automatic binding: In the React component, the context of each method points to an instance of the component, which automatically binds this to the current component.

What is the difference between React high-order components, Render props, hooks, and why iterate over them

These are the main ways react addresses code reuse:

  • HOC is an advanced technique used in React to reuse component logic. HOC itself is not part of the React API; it is a design pattern based on the composite features of React. Specifically, a higher-order component is a function that takes a component and returns a new component.
  • Render props is a simple technique for sharing code between React components using a prop with a function value. More specifically, render Prop is a function prop that tells components what to render.
  • Typically, the render props and higher-order components render only one child node. It’s much easier to let hooks serve this usage scenario. There is still room for both patterns (for example, a virtual scrollbar component might have a RenderLTEM property, or a visible container component might have its own DOM structure). But in most scenarios, hooks are sufficient and can help reduce nesting

HOC

Function withSubscription(WrappedComponent, selectData) { return class extends React.Component { constructor(props) { super(props); this.state = { data: selectData(DataSource, props) }; } // Some generic logic to render() {//... And render the wrapped component with the new data! return <WrappedComponent data={this.state.data} {... this.props} />; }}; // Use const BlogPostWithSubscription = withSubscription(BlogPost, (DataSource, props) => DataSource.getBlogPost(props.id)); HOC is a component design pattern in which HOC takes a component with additional parameters (if needed) and returns a new component. HOC is a pure function and has no side effects: it takes logic and doesn't affect the internal logic of the wrapped component. Disadvantages: The props that hoc passes to the wrapped component easily have the same name as the wrapped component and can be overwrittenCopy the code

Render props

Props is passed when the component is called

DataProvider extends React.Components {state = {name: DataProvider extends React.Components {state = {name: DataProvider extends React.Components {state = {name: DataProvider extends React.Components {state = {name: 'Tom'} render() {return (<div> <p> </p> {this.props. Render (this.state)} </div>); <DataProvider render={data => (<h1>Hello {data.name}</h1>)}/> "Render prop" is a prop that uses a function between React components Components with Render Prop accept a function that returns the React element, injecting Render's rendering logic into the component. Here, the naming of "render" could be any other valid identifier advantage: data sharing, code reuse, passing state within the component as props to the caller, rendering logic to the caller. Disadvantages: Unable to access data outside the return statement, not elegant nestingCopy the code

Hooks

// Customize a hook function useSubscription() {const data = DataSource. GetComments (); return [data]; } // function CommentList(props) { const {data} = props; const [subData] = useSubscription(); . } // Using <CommentList data='hello' /> allows you to use state and other React features without writing classes. As can be seen above, hook solves the problem of prop coverage of Hoc and the nested hell of render props in a way that solves the problem of nested hell of Hoc. Hook has the following advantages: - intuitive use; - Fixed prop name on Hoc - Fixed nested hell for render props due to sharing data - Can use data outside of return. Note that hooks can only be used at the top level of a component, not in branch statements.Copy the code

conclusion

Hoc, Render props, and hooks are all designed to solve the problem of code reuse, but both Hoc and Render props have specific usage scenarios and obvious disadvantages. Hook is a new API in update act16.8 that makes reuse of component logic simpler and addresses some of the shortcomings of Hoc and render props

An understanding of React-Fiber, what problems does it solve?

React V15 recursively compares the VirtualDOM tree while rendering, finding nodes that need to be changed and updating them synchronously. During this process, React will hog browser resources, which will cause user-triggered events to go unresponded, and will cause frames to drop, causing the user to feel stuck.

In order to give users the “illusion” of rapid application, one task should not hog resources for long. The browser’s rendering, layout, drawing, resource loading (such as HTML parsing), event response, and script execution can be regarded as “processes” of the operating system. CPU resources need to be properly allocated through certain scheduling policies to improve the user response rate of the browser and take into account the task execution efficiency.

React uses Fiber architecture to make this process interruptible. In addition to allowing the browser to respond to user interactions in a timely manner, giving away CPU execution has other benefits:

  • Batch delay is used to operate DOM to avoid operating a large number of DOM nodes at one time, which can achieve better user experience.
  • Give the browser a break and it will JIT the code and hotcode optimizations, or fix reflow.

Core idea: Fiber is also called coroutine or Fiber. Unlike threads, coroutines don’t have concurrency or parallelism in their own right (they need to work with threads), but are a mechanism for ceding control over the flow. Release execution from the CPU so that it can perform other operations during that time. The rendering process can be interrupted, and control can be handed back to the browser for higher-priority tasks, and the rendering can be resumed when the browser is idle

React.component.react.pureComponent

PureComponent represents a PureComponent that can be used to optimize React applications to reduce the number of times the render function is executed, thereby improving component performance.

In React, when prop or state changes, you can prevent the page from updating by returning false in the shouldComponentUpdate lifecycle function, thus reducing unnecessary render execution. React.PureComponent shouldComponentUpdate automatically.

However, shouldComponentUpdate() in pureComponent makes a shallow comparison, which means that references to data types are only compared to different addresses, not to the same address. Shallow comparisons ignore attribute and/or state mutations, i.e. the data reference pointer does not change and render will not be executed when the data changes. If you need to re-render then you need to re-open the spatial reference data. PureComponent is typically used for pure presentation components.

Advantage of using pureComponent: When a component is updated, the render function does not fire if neither the props or state of the component changes. The process of virtual DOM generation and comparison is eliminated to improve performance. This is because React automatically makes a shallow comparison

What are the differences and connections between Component, Element and Instance?

  • Element: An element element is a plain object that describes how you want a DOM node or other component to appear on the screen. The element Element can contain other elements in its properties props. Creating a React element element is cheap. The element Element is immutable once created.

  • Components: A component component can be declared in a number of ways. It can be a class with a render() method or, more simply, a function. In both cases, it takes the properties props as input and a tree of elements returned as output.

  • Instance: An instance is what you refer to in the component class you write with the keyword this. It is useful for storing local state and responding to life cycle events.

Functional Components have no instance at all. The Class component has instance, but you never need to create an instance of the component directly, because React does that for us

What are the differences between React. CreateClass and extends Component?

(1) Grammatical differences

  • CreateClass is essentially a factory function and extends more closely resembles the class writing of the latest ES6 specification. The syntactic differences between the two approaches are mainly in the definition of methods and the declaration of static attributes.
  • The createClass method definitions are separated by commas, because the creatClass is essentially a function that is passed an Object. Do not use commas to separate methods. This is the ES6 class syntax.

(2) propType and getDefaultProps

  • React. CreateClass: Sets and gets props using the propTypes object and the getDefaultProps() method.
  • React.component. propTypes and defaultProps by setting two properties

(3) The difference between states

  • React. CreateClass: Returns an object containing the initial value via the getInitialState() method
  • React.component: Sets the initial state by constructor

(4) This distinction

  • React.createClass: this will bind correctly
  • React.ponent: This is slightly different because ES6 is used, and properties are not automatically bound to instances of the React class.

(5) Mixins

  • React. CreateClass: With React. CreateClass, you can add a property called mixins when you create a component and assign an array of classes that can be mixed to mixins.
  • If you use ES6 to create components, thenReact mixins“Will no longer be available.

React High-order components React high-order components React high-order components React high-order components React high-order components React high-order components React high-order components React high-order components React high-order components React high-order components React high-order components React

HOC is a function that takes a component as an argument and returns a new component. It is just a component design pattern, which is inevitably generated by the combinatorial nature of React itself. We call them pure components because they can accept any dynamically supplied child component, but they do not modify or copy any behavior in their input component.

Function withSubscription(WrappedComponent, selectData) { return class extends React.Component { constructor(props) { super(props); this.state = { data: selectData(DataSource, props) }; } // Some generic logic to render() {//... And render the wrapped component with the new data! return <WrappedComponent data={this.state.data} {... this.props} />; }}; // Use const BlogPostWithSubscription = withSubscription(BlogPost, (DataSource, props) => DataSource.getBlogPost(props.id));Copy the code

Pros and cons of HOC

  • Advantages: Logical use, does not affect the internal logic of the packaged components.
  • Disadvantages: The props that hoc passes to the wrapped component easily have the same name as the wrapped component and can be overwritten

Applicable scenario

  • Code reuse, logic abstraction
  • Rendering hijacked
  • State abstracts and changes
  • Props to change

Understanding of componentWillReceiveProps

This method is invoked when props changes, but not when render is initialized. Inside this callback, you can update the component state by calling this.setState(), depending on the properties. The old properties can still be called by this.props. No additional render calls are triggered.

Usage benefit: In this lifecycle, it is possible to update the child component’s own state by obtaining new props before the render function of the child component executes. May perform data request here, and the need to pass parameters from componentWillReceiveProps (nextProps). You don’t have to put all requests in the parent component. The request is then made only when the component is rendering, reducing the request burden.

ComponentWillReceiveProps when initializing render will not perform, it will be accepted in the Component to the new state (Props) is triggered, commonly used in the parent Component state update subcomponents of rendering

What methods trigger React rerender?

  • The setState () method is called

SetState is the most commonly used command in React. In most cases, executing setState triggers render. But there is a point of concern here, setState does not necessarily re-render. Render is not triggered when setState is passed null

class App extends React.Component { state = { a: 1 }; render() { console.log("render"); return ( <React.Fragement> <p>{this.state.a}</p> <button onClick={() => { this.setState({ a: 1 }); <button onClick={() => this.setState(null)}>setState null</button> <Child /> </React.Fragement> ); }}Copy the code
  • The parent component is re-rendered

As soon as the parent component is rerendered, the child component will be rerendered, triggering render, even if the props of the child component passed in have not changed

What does rerendering render do?

  • The old and new VNodes are compared, which is called the Diff algorithm.
  • A depth-first traversal is carried out on the old and new trees, so that each node will have a mark. When it comes to the depth traversal, the node will be compared with the new node tree every time it reaches one or two nodes, and if there is any difference, it will be put into an object
  • Traverse the difference object, update the VNode according to the response rule according to the type of difference

React’s basic mindset for dealing with render is to rerender the entire application every time there is a change. Before Virtual DOM, the easiest way to do this was to call innerHTML directly. The great thing about Virtual DOM is not that it’s faster than manipulating the DOM directly, but that no matter how the data changes, the DOM is updated as cheaply as possible. React compares the virtual DOM tree returned by the Render function to the old one to determine if and how the DOM should be updated. When the DOM tree is large, traversing two trees for various comparisons can be quite costly, especially if a small change in setState at the top level defaults to traversing the entire tree. React uses a highly optimized Diff algorithm, but the process still takes a toll on performance.

How does React tell when to rerender components?

Component state changes can be made by props changes, or directly through the setState method. The component gets the new state, and React decides if the component should be rerendered. React rerenders the component whenever its state changes. This is because the shouldComponentUpdate method in React returns true by default, which is what causes every update to be rerendered.

When React is about to render a component, it executes the shouldComponentUpdate method to see if it returns true (the component should be updated, i.e. re-rendered). So we need to override the shouldComponentUpdate method to return true or false depending on the situation to tell React when to re-render and when to skip re-render.

What are the different ways to declare a React component?

React declares components in three ways:

  • Function definedStateless component
  • ES5 native modeReact.createClassDefined components
  • In the form of ES6extends React.ComponentDefined components

(1) Stateless function component it is used to create pure presentation component, which is only responsible for presenting according to the passed props. The operation component that does not involve the state state is not instantiated, and the overall rendering performance is improved. This object cannot be accessed, and lifecycle methods cannot be accessed

ES5 native react. createClass // RFC react. createClass will self-bind function methods, resulting in unnecessary performance overhead and increasing the possibility of stale code.

The react.createclass form will eventually be replaced by the react.createclass form, which is currently recommended by RCC. React.createClass is a better way to reuse code.

Stateless components differ from stateless components: In contrast to stateless components, both React. CreateClass and react.componentcreate stateful components that are instantiated and have access to the component’s lifecycle methods.

React.createclass differs from react.createclass:

① The function this is self-bound

  • CreateClass creates a component whose this is automatically bound to React for each member function. This in the function is set correctly.
  • React.Com ponent created component, its member function does not automatically binding this, need a developer manual binding, this won’t be able to access to current component instance objects.

(2) propTypes and defaultProps are configured differently

  • When a component is created, the properties of the component props and the default properties of the component are configured as properties of the component instance. DefaultProps uses the getDefaultProps method to obtain the default component properties
  • When react.componentconfigures these two corresponding information when creating a component, they are configured as properties of the component class, not as properties of the component instance, which are called static properties of the class.

3 The initial state of the component is configured differently

  • React.createClass creates a component whose state state is configured using the getInitialState method.
  • React.componentcreates a component whose state state is declared in Constructor as if it were initializing the component properties.

Understanding and usage scenarios of stateful and stateless components

(1) Stateful components

Features:

  • Is a kind of component
  • Have inherited
  • You can use this
  • You can use the React lifecycle
  • Life cycle hook functions are triggered frequently, which affects performance
  • Internal uses state to maintain changes in its own state. Stateful components render based on props and their own state passed in by external components.

Usage Scenarios:

  • Need to use state.
  • Use of stateless components. React hooks are also available.

Conclusion: Class components can maintain their own state variables, namely the state of the component. Class components also have different lifecycle methods, which give developers more control over components at different stages (mount, update, uninstall). Class components can act as either stateless or stateful components. A class component can also be called stateless when it does not need to manage its own state.

(2) Features of stateless components:

  • Does not depend on its own state state
  • It can be a class component or a function component.
  • You can avoid the this keyword entirely. (No binding required for arrow function events)
  • Higher performance. Stateless function components should be used first when lifecycle hooks are not needed
  • A component that does not maintain state internally and only renders according to props passed in by an external component. When the props changes, the component rerenders.

Usage Scenarios:

  • Components do not need to manage state, pure presentation

Advantages:

  • Simplify the code and focus on Render
  • Components do not need to be instantiated and have no life cycle, improving performance. The output (render) depends only on the input (properties), with no side effects
  • Decoupling of view and data

Disadvantages:

  • Unable to use ref
  • Lifecycle free methods
  • There is no control over the rerendering of the component because the shouldComponentUpdate method is not available and rerenders when the component receives a new property

Summary: Consider using state components for components that have internal state and are independent of external state, so that the state tree is not too complex to understand and manage. When a component does not need to manage its own state, that is, stateless components, it should be designed as functional components first. Such as custom , components

React Fragment Fragment Fragment Fragment Fragment Fragment Fragment Fragment Fragment Fragment Fragment

A common pattern in React is for a component to return multiple elements. Fragments allow you to group sublists without adding additional nodes to the DOM

In React, the element returned by a component can have only one root element. To avoid adding extra DOM nodes, you can use the Fragment tag to wrap all elements. The Fragment tag does not render any elements

import React, { Component, Fragment} from 'react' // Render () {return (< react. Fragment> <ChildA /> <ChildB /> <ChildC /> </ react. Fragment> ); Render () {return (<> <ChildA /> <ChildB /> <ChildC /> </>); }Copy the code

React How to obtain the DOM element of a component?

You can use ref to get an instance of a child node, and then directly get the child node instance through some specific properties of the current class component instance. Ref can be implemented in three ways:

  • String format: string format, which was most commonly used prior to release 16, for example:<p ref="info">span</p>
  • Function format: ref corresponds to a method that takes one argument, the corresponding node instance, for example:<p ref={ele => this.info = ele}></p>
  • CreateRef: An API provided by React 16, implemented using react.createref ()

Can refs be accessed in Render in React? Why is that?

No, the DOM has not been generated in the Render phase, so you cannot obtain the DOM. DOM is acquired in pre-commit and COMMIT phases:

Marketplacers (Portals) of React, how to use them, and what are the application scenarios

Portals is an official solution provided by React 16 that allows components to be mounted anywhere in the DOM tree outside of the parent component hierarchy. In plain English, we render a component whose DOM structure is not in the component.

ReactDOM.createPortal(child, container); - The first argument child is a renderable React child, such as an element, string, or fragment; - The second argument container is a DOM elementCopy the code
import DemoComponent from './DemoComponent'; Render () {return (<div id="parent"> <DemoComponent /> </div>); } Normally, the element returned by a component's render function will be mounted on its parent componentCopy the code

However, some elements need to be mounted at a higher level. Typical application scenario: when the parent component has overflow: Hidden or Z-index style Settings, the component may be obscured by other elements. In this case, you can consider whether to use Portal to mount the component away from the parent component. For example: dialog box, modal window

How to avoid unnecessary render in React?

React is based on the perfect combination of virtual DOM and efficient Diff algorithms to achieve minimal granularity updates to the DOM. For the most part, React renders the DOM efficiently enough to be business-as-usual. However, performance issues still plague us in individual complex business scenarios. At this point, some steps need to be taken to improve performance, one of which is to avoid unnecessary Render. Here are the optimization points:

  • ShouldComponentUpdate and PureComponent

In React components, shouldComponentUpdate or PureComponent can be used to reduce the need for child components to render due to parent component updates. ShouldComponentUpdate to determine whether the component should be rerendered or not, return false if you don’t want the component to be rerendered.

  • Leverage higher-order components

ShouldComponentUpdate: shouldComponentUpdate: shouldComponentUpdate: shouldComponentUpdate: shouldComponentUpdate: shouldComponentUpdate: shouldComponentUpdate: shouldComponentUpdate: shouldComponentUpdate: shouldComponentUpdate

  • Use the React. Memo

Memo is a new API for React 16.6 that caches component renderings to avoid unnecessary updates. The memo is also a higher-order component, similar to PureComponent, except that it can only be used for function components.

What do you understand about React-Intl? How does it work?

React-intl is part of FormatJS, Yahoo’s open source language internationalization project, which provides components and apis that can be bundled with ReactJS.

React-intl provides two methods: one is to use the React component, and the other is to call the API directly. It is recommended to use the React component in React projects. Only when the React component is not available, you should call the API provided by the framework. React provides a range of React components, including number formatting, string formatting, date formatting, and more.

In React-Intl, you can configure different language packages. It works by switching between language packages as required.

React Context

In React, data is transferred using props to maintain one-way data flow, which makes the relationship between components simple and predictable. However, one-way data flow is not applicable in some scenarios. There is nothing wrong with just a pair of parent and child components, but if there are layers of dependencies between components, props need to be layered. Obviously, this is too cumbersome.

Context provides a way to share such values between components without explicitly passing props layer by layer through the component tree.

You can think of the context as a shared store within a particular component tree for data transfer. Simply put, when you don’t want to pass props or state layer by layer in the component tree, you can use Context to pass component data across layers.

During the execution of THE JS code block, a corresponding scope chain will be created. This scope chain records the active objects that can be accessed during the execution of the JS code block at runtime, including variables and functions. The JS program accesses variables and functions inside or outside the code block through the scope chain.

Using the JS chain of scopes as an analogy, the React component provides the Context as a scope for child components to access, and the properties of the Context can be thought of as live objects in the scope. Since a component’s Context is composed of the Context object returned by getChildContext () from all components in the parent chain, the component can access the properties of the Context provided by all components in the parent chain.

Why does React not recommend using Context first?

  • Context is still in the experimental stage and may change a lot in future releases. In fact, this has already happened, so it is not recommended to use Context in app to avoid major impact and trouble in future upgrades.

  • Although it is not recommended to use context in app, for unique components, because the scope of influence is smaller than that of app, if you can achieve high cohesion and do not break the dependencies between component trees, you can consider using context

  • For data communication or state management between components, use props or state, and then consider using a mature third-party library. Context should be considered when either of the above methods is not the best solution.

  • Context updates need to be triggered by setState(), but this is not very reliable. Context supports cross-component access, but if the middle child does something that doesn’t affect the update, For example, shouldComponentUpdate() returns false, there is no guarantee that the Context can be updated using the child components of the Context

What are controlled and non-controlled components in React?

(1) When a controlled component uses a form to collect user input, such as < SELECT >< TexteArea > and other elements, it must bind a change event. When the state of the form changes, the onChange event will be triggered to update the state of the component. This type of component is called a controlled component in React. In a controlled component, the rendered state of the component corresponds to its value or Checked property. React eliminates the local state of the component in this way and makes the overall state controllable. React officially recommends using controlled forms components.

The process of updating state for controlled components:

  • You can set the default value of the form in the initial state
  • The onChange event handler is called every time the value of the form changes
  • The event handler gets the changed state from the event object E and updates the component’s state
  • Once the state is updated with the setState method, the view is rerendered and the form component is updated

Controlled component defects: the values of form elements are run by the React components, when there are multiple input box, or multiple this component, if you want to get at the same time to the entire value must be each to write the event handler, it will make the code be bloated, so in order to solve this kind of situation, the uncontrolled components.

A form component is an uncontrolled component if it has no value props (radio and check buttons are checked props). In uncontrolled components, you can use a REF to get form values from the DOM. Instead of writing an event handler for each status update.

Conclusion: The DOM of all input classes in the page is called uncontrolled component if it is used and retrieved. The input value is maintained in state through setState and retrieved from state when needed. The data here is controlled by state and called controlled component.

What does refs do in React? What are the application scenarios?

Refs provides a way to access React elements or DOM nodes created in the Render method. Refs should be used with caution. Refs are suitable for the following scenarios:

  • Handles focus, text selection, or media control
  • Trigger the necessary animation
  • Integrate third-party DOM libraries
class MyComponent extends React.Component { constructor(props) { super(props) this.myRef = React.createRef() } render() {return <div ref={this.myref} />}} Refs are created using the 'react.createref ()' method, which attaches to the React element via the 'ref' attribute. To use Refs throughout the component, assign 'ref' to the instance property in the constructorCopy the code
Function CustomTextInput(props) {// We must declare textInput so that the ref callback can reference it. function handleClick() { textInput.focus(); } return ( <div> <input type="text" ref={(input) => { textInput = input; }} /> <input type="button" value="Focus the text input" onClick={handleClick} /> </div> ); } Because function components have no instances, Refs cannot be used directly on function components, but can be used inside function components with the help of closuresCopy the code

Note:

  • Refs should not be overused

  • The return value of ref depends on the type of node:

    • whenrefWhen the attribute is applied to a normal HTML element,React.createRef()Will receive the underlying DOM element as hiscurrentProperty to createref.
    • whenrefProperty is used for a custom class component,refObject will receive the mounted instance of the component as itscurrent.
  • Pass Refs or callback Refs can be used when a parent component needs to access a REF in a child component

What does the React component’s constructor do? Is it required?

Constructors serve two purposes:

  • Initialize the local state by assigning the object to this.state
  • Bind event handler methods to instances

So, when you need to initialize state or bind events in React class, you need to add constructors

class LikeButton extends React.Component { constructor() { super(); this.state = { liked: false }; this.handleClick = this.handleClick.bind(this); } handleClick() { this.setState({liked: ! this.state.liked}); } render() { const text = this.state.liked ? 'liked' : 'haven\'t liked'; return ( <div onClick={this.handleClick}> You {text} this. Click to toggle. </div> ); } } ReactDOM.render( <LikeButton />, document.getElementById('example') ); The constructor is used to create the this object of the parent class; Subclasses must call the super method from the constructor method; Otherwise, an error occurs when creating a new instance. Because subclasses don't have their own This object, they inherit the parent's this object and then process it. If the super method is not called; Subclasses don't get this objectCopy the code

Note:

  • Constructor () must be accompanied by super(). If this. Props is to be used inside constructor, pass props otherwise
  • Bind in JavaScript returns a new function each time, and for performance reasons, try to bind events in constructor

ForwardRef? What does it do?

The React. ForwardRef creates a React component that forwards the ref properties it receives to another component in its component tree. This technique is uncommon, but is particularly useful in two scenarios:

  • Forward refs to the DOM component
  • Forwarding refs in higher-order components

What are the similarities and differences between class components and function components?

Similarities: Components are the smallest snippets of code reusable for React, and they return React elements to render on the page. Because the React component is the smallest coding unit, both function components and class components are used in exactly the same way and rendered in the end.

We can even rewrite a class component into a function component, or a function component into a class component (although this refactoring behavior is not recommended). From a user perspective, it is difficult to distinguish between the two in terms of user experience, and in modern browsers the performance of closures and classes differs significantly only in extreme scenarios. As a result, the two can be considered essentially identical as components.

Difference:

  • They have very different mental models at the time of development. Class component is based on object-oriented programming, it is the main inheritance, life cycle and other core concepts; The functional component kernel is functional programming, which is immutable, has no side effects, transparent reference, and so on.
  • Previously, in the usage scenario, if there is a component that needs to use the life cycle, then the class component is promoted; Design patterns, if inheritance is needed, push the class component. But now function components can completely replace class components thanks to React Hooks, which have made life cycles obsolete. Secondly, inheritance is not the best design mode for components. The official advocates the design concept of “combination is better than inheritance”, so the advantages of class components in this aspect are fading out.
  • In terms of performance optimization, the class component mainly relies on shouldComponentUpdate to block rendering to improve performance, while the function component relies on react.Memo to cache rendering results to improve performance.
  • Class components are much easier to learn, but function components are the future of the community thanks to React Hooks.
  • Class components are not easy to optimize in the future time slice and concurrent mode due to the complexity of the life cycle. The function component itself is lightweight and simple. Based on Hooks, it provides more fine-grained logic organization and reuse than the original, and can better adapt to the future development of React.