What are the top-level API s of React?

1, Introduction

The React library provides the following API s, which can be called directly.

2, Create element
1,createElement()
  • Function: create React element.

    // Function prototype
    React.createElement(
        type,
        [props],
        [...children]
    )
  • There are two ways to create elements:

    • Using JSX to create an element does not need to call createElement(), and the preprocessor babel will handle it

      // Creating elements and components using jsx
      class Hello extends React.Component {
          render() {
              return <div>Hello {this.props.toWhat}</div>;
          }
      }
      
      ReactDOM.render(
          <Hello toWhat="World" />,
          document.getElementById('root')
      );
    • If you do not use JSX to create an element, you need to call createElement()

      // Creating elements and components without jsx
      class Hello extends React.Component {
          render() {
              return React.createElement('div', null, `Hello ${this.props.toWhat}`);
          }
      }
      
      ReactDOM.render(
          React.createElement(Hello, { toWhat: 'World' }, null),
          document.getElementById('root')
      );
3, Element manipulation API
1,cloneElement()
  • Function: copy to generate a new element.

    // Function prototype
    React.cloneElement(
        element,
        [config],
        [...children]
    )
    // config: contains new props, key or ref
  • Equivalent to jsx

    React.cloneElement()
    // Almost equivalent to the following jsx writing
    < element.type {...element.props } {...props }> { children }</element.type >
2,isValidElement()

Verify whether the object is a React element, and the return value is true or false.

React.isValidElement(object)
4, Child element operation API

React.Children function: you can traverse and access child elements, and access the attribute this.props.children, which can't access data.

1,React.Children.map
  • Function: traverse child elements and return an array. The function prototype is as follows:

    React.Children.map(children, function)
  • Use case: traverse and copy child elements

    const Child = () => (
        <div>child</div>
    )
    
    class App extends React.Component {
        render() {
            const template1 = React.Children.map(this.props.children, (child) => {
                return React.cloneElement(child);
            });
    
            return template1;
        }
    }
2,React.Children.forEach
  • Function: the same as React.Children.map, except that the return value is not an array.

    React.Children.forEach(children, function)
3,React.Children.count
  • Function: returns the total number of components in children, which is equal to the number of calls to the callback function through map or forEach.

    React.Children.count(children)
4,React.Children.only
  • Function: verify whether children have only one child node (React element). If so, return it. Otherwise, this method will throw an error.

    React.Children.only(children)
  • Note: React.Children.only() does not accept the return value of React.Children.map() because it is an array and not a React element.
5, Component related API s
1,React.Component
  • Function: use ES6 classes Define the base class of React component in the following way:

    class Greeting extends React.Component {
        render() {
            return <h1>Hello, {this.props.name}</h1>;
        }
    }
2,React.PureComponent
  • Function: like React.Component, you can inherit them to implement components.
  • Difference: React.PureComponent implements shouldComponentUpdate(), but React.Component does not. React.PureComponent performs component rendering only when the prop and state data change, which can be used for component performance optimization.
  • Two points to note:

    • When determining whether the prop and state data change, a comparison operation will be performed. This comparison operation is only suitable for simple data structures, not complex data structures. Please ensure that the prop and state objects are not complex data structures.
    • Ensure that all child components also inherit React.PureComponent.
3,React.memo
  • Function: it is a high-level component that can wrap other components to improve performance.
  • Principle: React.memo will monitor the changes of props attribute of components. Only the changes can be re rendered, otherwise the rendering operation will be skipped.

    const MyComponent = React.memo(function MyComponent(props) {
        /* Rendering with props */
    });
  • Two points to note:

    • If useState and useContext are used in the React.memo component, the React.memo component will render again when the state and context values change.
    • React.memo can't monitor the changes of props of complex data structure, so it needs to customize the comparison function to monitor the complex data structure.

      function MyComponent(props) {
          /* Rendering with props */
      }
      function areEqual(prevProps, nextProps) {
          /*
          If nextProps is passed into the render method, the returned result is the same as
          If the return results of prevProps passed into render method are consistent, true will be returned,
          Otherwise, false is returned
          */
      }
      export default React.memo(MyComponent, areEqual);
6, Delayed loading

When rendering a page, you can not load unused components.

1,React.lazy
  • Function: delay loading unused components, relying on react.suspend

    // This component is dynamically loaded
    const SomeComponent = React.lazy(() => import('./SomeComponent'));
  • Note: using the dynamic import feature of React.lazy requires the JS environment to support Promise. In IE11 and below browsers, you need to use this feature by introducing polyfill.
2,React.Suspense
  • Name: Specifies the loading indicator
  • Function: cooperate with React.lazy to complete delayed loading.

    // The component is dynamically loaded
    const OtherComponent = React.lazy(() => import('./OtherComponent'));
    
    function MyComponent() {
        return (
            // Display the < spinner > component until OtherComponent is loaded
            <React.Suspense fallback={<Spinner />}>
                <div>
                    <OtherComponent />
                </div>
            </React.Suspense>
        );
    }
7, Other API s
1,React.Fragment
  • Function: let render() return multiple elements without creating additional DOM elements. Use details, Look here
2,React.createRef
  • Function: create a ref object to point to the component, so that other components can easily access its internal data and methods. Use details, Look here
3,React.forwardRef
  • Function: React.forwardRef will create a React component. The new component can forward the passed in ref object to the child elements.
  • There are two usage scenarios: forwarding refs to DOM components and forwarding refs in high-level components. Details, Look here
8, Reference documents:

Tags: React api

Posted on Tue, 30 Nov 2021 17:49:35 -0500 by reinaldo