React Three Ways to Create Components and Their Differences

  • 2021-07-10 18:41:45
  • OfStack

After the introduction of React, there have been three ways to define react components for different reasons, and all roads lead to the same goal; Three specific ways:

Functionally defined stateless components es5 Native Mode React. createClass Defined Components Components defined by extends React. Component in the form of es6

Although there are three ways to define components of react, what are the differences among these three ways to define components? Or why is there a corresponding definition? The following is a brief introduction.

Stateless functional component

The form of creating stateless functional components has been around since React 0.14. It is intended to create a pure presentation component that is only responsible for presenting according to the props passed in, and does not involve operations that require state state. Specific stateless functional components, its official point out:

In most React code, most components are written as stateless components, which can be built into other components through simple combination; This design pattern, which combines multiple simple applications into one large application, is advocated.

The stateless functional component is a component class with only one render method, which is created in the form of function or ES6 arrow function, and the component has no state state. The specific creation form is as follows:


function HelloComponent(props, /* context */) {
 return <div>Hello {props.name}</div>
}
ReactDOM.render(<HelloComponent name="Sebastian" />, mountNode) 

The creation form of stateless components makes the code readable better, and reduces a lot of redundant code, which is reduced to only one render method, which greatly enhances the convenience of writing one component. In addition, stateless components have the following remarkable characteristics:

1. Components are not instantiated and overall rendering performance is improved

Because the component is reduced to a function of render method, because it is a stateless component, the stateless component will not be in the process of component instantiation, and the non-instantiation process will not need to allocate redundant memory, thus the performance will be improved by 1.

2. Components cannot access this objects

Stateless components cannot access objects in component this because there is no instantiation process, for example, this. ref, this. state, etc. You can't create components in this form if you want to access them

3. Component cannot access lifecycle methods

Because stateless components do not require component lifecycle management and state management, the underlying implementation of this form of components does not implement the component lifecycle approach. Therefore, stateless components cannot participate in the life cycle management of components.

4. The stateless component can only access the input props, and the same props will get the same rendering result without side effects

Stateless components are encouraged to divide the originally huge components in a simple way in large projects. In the future, React will also make a series of optimizations for stateless components in areas such as meaningless inspection and memory allocation, so try to use stateless components whenever possible.

React.createClass

'React. createClass' is the first recommended way for react to create a component, an React component implemented by the native JavaScript of ES 5, in the following form:


var InputControlES5 = React.createClass({
 propTypes: {// Define incoming props Various types of attributes in 
 initialValue: React.PropTypes.string
 },
 defaultProps: { // Component default props Object 
 initialValue: ''
 },
 //  Settings  initial state
 getInitialState: function() {// Component-related state objects 
 return {
 text: this.props.initialValue || 'placeholder'
 };
 },
 handleChange: function(event) {
 this.setState({ //this represents react component instance
 text: event.target.value
 });
 },
 render: function() {
 return (
 <div>
 Type something:
 <input onChange={this.handleChange} value={this.state.text} />
 </div>
 );
 }
});
InputControlES6.propTypes = {
 initialValue: React.PropTypes.string
};
InputControlES6.defaultProps = {
 initialValue: ''
};

In contrast to stateless components, React. createClass and React. Component, described later, both create stateful components that are to be instantiated and have access to their lifecycle methods. However, with the development of React, the problems of React. createClass form itself are exposed:

React. createClass can self-bind function methods (unlike React. Component, which only bind functions that need to be cared for), resulting in unnecessary performance overhead and increasing the possibility of code obsolescence. mixins of React. mixins is not natural and intuitive enough; The React. Component format is perfect for higher-order components (Higher Order Components-HOC), which shows more powerful functions than mixins in a more intuitive form, and HOC is pure JavaScript, so there is no need to worry that they will be discarded.

React.Component

React. Component creates react components in the form of ES6, which is highly recommended by React to create stateful components at present, and will eventually replace React. createClass; Compared with React. createClass can realize code reuse better. Replace the form React. createClass above with React. Component in the following form:


class InputControlES6 extends React.Component {
 constructor(props) {
 super(props);
 //  Settings  initial state
 this.state = {
 text: props.initialValue || 'placeholder'
 };
 // ES6  Functions in the class must be bound manually 
 this.handleChange = this.handleChange.bind(this);
 }
 handleChange(event) {
 this.setState({
 text: event.target.value
 });
 }
 render() {
 return (
 <div>
 Type something:
 <input onChange={this.handleChange}
 value={this.state.text} />
 </div>
 );
 }
}
InputControlES6.propTypes = {
 initialValue: React.PropTypes.string
};
InputControlES6.defaultProps = {
 initialValue: ''
};

The difference between React. createClass and React. Component

In addition to the syntax format of the components defined by the two in the code shown above, there are many important differences between the two, and the main differences between the two under 1 are described below.

Function this self-binding

React. createClass to create a component, its this of each member function has React automatic binding, any time to use, directly use this. method can, this in the function will be set correctly.


const Contacts = React.createClass({ 
 handleClick() {
 console.log(this); // React Component instance
 },
 render() {
 return (
 <div onClick={this.handleClick}></div>
 );
 }
});

React. Component created components, its member functions will not automatically bind this, the developer needs to bind manually, otherwise this can not get the current component instance object.


class Contacts extends React.Component { 
 constructor(props) {
 super(props);
 }
 handleClick() {
 console.log(this); // null
 }
 render() {
 return (
 <div onClick={this.handleClick}></div>
 );
 }

Of course, there are three manual binding methods for React. Component: you can bind in the constructor, you can bind with method. bind (this) at call time, and you can bind with arrow function. Take the handleClick function in the above example, and its binding can have:


 constructor(props) {
 super(props);
 this.handleClick = this.handleClick.bind(this); // Binding in constructor 
 }

<div onClick={this.handleClick.bind(this)}></div> //使用bind来绑定

<div onClick={()=>this.handleClick()}></div> //使用arrow function来绑定

Component property type propTypes and its default props property defaultProps are configured differently

React. createClass When creating a component, the attribute type of the component props and the default attribute of the component will be configured as the attribute of the component instance, in which defaultProps uses the method of getDefaultProps to obtain the default component attribute


const TodoItem = React.createClass({
 propTypes: { // as an object
 name: React.PropTypes.string
 },
 getDefaultProps(){ // return a object
 return {
 name: '' 
 }
 }
 render(){
 return <div></div>
 }
})

React. Component When configuring these two correspondence information when creating a component, they are configured as properties of the component class, not the component instance, or so-called static properties of the class. Corresponding to the above configuration is as follows:


class TodoItem extends React.Component {
 static propTypes = {// Static properties of the class 
 name: React.PropTypes.string
 };
 static defaultProps = {// Static properties of the class 
 name: ''
 };
 ...
}

The configuration of component initial state state is different

React. createClass, whose state state is to configure the state related to the component by getInitialState method;

React. Component creates a component whose state state is declared in constructor as it initializes component property 1.


const TodoItem = React.createClass({
 // return an object
 getInitialState(){ 
 return {
 isEditing: false
 }
 }
 render(){
 return <div></div>
 }
})

class TodoItem extends React.Component{
 constructor(props){
 super(props);
 this.state = { // define this.state in constructor
 isEditing: false
 } 
 }
 render(){
 return <div></div>
 }
}

Support for Mixins varies

Mixins (blending) is an implementation of object-oriented programming OOP. Its function is to reuse common codes. The common codes are extracted into an object, and then Mixins into the object to achieve code reuse.

React. createClass You can use the mixins property to mix a collection of classes as an array when creating a component.


var InputControlES5 = React.createClass({
 propTypes: {// Define incoming props Various types of attributes in 
 initialValue: React.PropTypes.string
 },
 defaultProps: { // Component default props Object 
 initialValue: ''
 },
 //  Settings  initial state
 getInitialState: function() {// Component-related state objects 
 return {
 text: this.props.initialValue || 'placeholder'
 };
 },
 handleChange: function(event) {
 this.setState({ //this represents react component instance
 text: event.target.value
 });
 },
 render: function() {
 return (
 <div>
 Type something:
 <input onChange={this.handleChange} value={this.state.text} />
 </div>
 );
 }
});
InputControlES6.propTypes = {
 initialValue: React.PropTypes.string
};
InputControlES6.defaultProps = {
 initialValue: ''
};
0

Unfortunately, React. Component does not support Mixins. So far, the React team has not given an official solution in this form; But the React developer community offers a new way to replace Mixins, that is, Higher-Order Components.

How do I choose which way to create a component

Since the React team has stated that React. createClass will eventually be replaced by the class form of React. Component. However, the React. createClass form will not be discarded until an alternative to Mixins is found. So:

If you can create components with React. Component, try not to create components with React. createClass.

In addition, the form selection of creating components should also be determined according to the following:

1. Whenever possible, use stateless component creation forms.

2. Otherwise (e.g. state, lifecycle approach, ref, etc.), create the component using the es6 form ` React. Component '


Related articles: