What are the three ways React creates components and what are the differences?

1. Stateless functional components

It is to create a pure display component, this component is only responsible for displaying based on the incoming props, does not involve the operation of the state state

The component will not be instantiated, the overall rendering performance will be improved, this object cannot be accessed, and the life cycle methods cannot be accessed

2. ES5 Native Way React.createClass // RFC

React.createClass will self-bind function methods, causing unnecessary performance overhead and increasing the possibility of code obsolescence.

3. E6 inheritance form React.Component // RCC

The currently highly recommended way to create stateful components will eventually replace the React.createClass form; code reuse can be better achieved than React.createClass.

The difference between stateless components and the latter two

Compared with stateless components, both React.createClass and React.Component create stateful components, which are to be instantiated and have access to component lifecycle methods.

Difference between React.createClass **** and React.Component

① Function this self binding

  • For the component created by React.createClass, this of each member function is automatically bound by React, and this in the function will be set correctly.

  • For the components created by React.Component, its member functions will not be automatically bound to this, and developers need to manually bind it, otherwise this cannot obtain the current component instance object.

② The component property type propTypes and its default props property defaultProps are configured differently

  • When React.createClass creates a component, the property type of the component props and the default properties of the component will be configured as the properties of the component instance, where defaultProps uses the method of getDefaultProps to get the default component properties

  • When React.Component configures these two corresponding information when creating a component, they are configured as properties of the component class, not the properties of the component instance, which is also called the static properties of the class.

③ The configuration of the initial state of the component is different

  • The state of the component created by React.createClass is to configure the related state of the component through the getInitialState method;

  • The state of the component created by React.Component is declared in the constructor like initializing component properties.

Final summary

Whenever possible, use stateless component creation.

Components that can be created with React.Component try not to create components in the form of React.createClass to enhance reusability and improve performance.

 

Published 203 original articles · praised 8 · 10,000+ views

Guess you like

Origin blog.csdn.net/z591102/article/details/105575081