Three methods for creating a React component and their differences, three methods for creating a react component

Source: Internet
Author: User

Three methods for creating a React component and their differences, three methods for creating a react component

After the release of React, three methods of defining react components were successively introduced for different reasons, with the same things in the same way. Three methods are specific:

  • Stateless component defined by function
  • Es5 native component defined by React. createClass
  • Components defined by extends React. Component in es6 form

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

Stateless functional components

The creation of a stateless functional component starts with React 0.14. It is used to create a pure display component. This component is only displayed based on the passed props and does not involve operations that require state. The specific stateless function component is officially pointed out:

In most React code, most components are written as stateless components and can be constructed into other components through simple combinations; this design model, which is then combined into a large application, is promoted.

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

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

The creation of stateless components makes the code more readable, reduces a lot of redundant code, and simplifies to only one render method, greatly enhancing the convenience of writing one component, in addition, stateless components have the following notable features:

1. components are not instantiated, and the overall rendering performance is improved.

The component is reduced to a function of the render method. Because the component is a stateless component, the stateless component will not be instantiated in the component process, no extra memory needs to be allocated during the non-instantiation process, thus improving the performance.

2. components cannot access this object

The stateless component does not have an instantiation process, so it cannot access objects in the component this, such as this. ref and this. state. You cannot use this method to create components if you want to access them.

3. Methods for Component Access to the lifecycle

Because stateless components do not require component lifecycle management and State management, the underlying implementation of such components will not implement the component lifecycle method. Therefore, stateless components cannot be involved in the lifecycle management of components.

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

Stateless components are encouraged to separate the original large components in a large project in a simple way, in the future, React will perform a series of optimizations for stateless components, such as meaningless checks and memory allocation.Use stateless components whenever possible.

React. createClass

'React. createClass 'is a React-first recommended method for creating components. This is a react component implemented by ES5's native JavaScript. Its form is as follows:

Var InputControlES5 = React. createClass ({propTypes: {// defines attributes of various types in the imported props initialValue: React. propTypes. string}, defaultProps: {// default props object of the component initialValue: ''}, // set initial state getInitialState: function () {// return {text: this. props. initialValue | 'placeholder '};}, handleChange: function (event) {this. setState ({// this represents react component instance text: event.tar get. 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 :''};

Compared with stateless components, React. createClass and the React. component is used to create stateful components that need to be instantiated and can access the life cycle method of the Component. However, with the development of React, problems in the form of React. createClass are exposed:

  • React. createClass automatically binds Function Methods (unlike React. Component, which only binds functions that need to be concerned), causing unnecessary performance overhead and increasing the possibility of code expiration.
  • React. the mixins of createClass are not natural and intuitive; React. the Component form is very suitable for high-Order Components (Higher Order Components -- HOC). It presents more powerful functions than mixins in a more intuitive form, and HOC is pure JavaScript, don't worry that they will be abandoned.

React. Component

React. component is used to create react components in the form of ES6. It is currently highly recommended by React to create stateful components and will eventually replace React. createClass format; relative to React. createClass can achieve better code reuse. Change the React. createClass format to React. Component format as follows:

Class InputControlES6 extends React. component {constructor (props) {super (props); // set the initial state this. state = {text: props. initialValue | 'placeholder '}; // The function must be manually bound to this. handleChange = this. handleChange. bind (this);} handleChange (event) {this. setState ({text: event.tar get. value});} render () {return (<div> Type something: <input onChange = {this. handleChange} value = {this. state. text}/> </div>) ;}} InputControlES6.propTypes = {initialValue: React. propTypes. string}; InputControlES6.defaultProps = {initialValue :''};

Difference between React. createClass and React. Component

There are many important differences between the two defined components based on their syntax formats. The main differences are described below.

Function this self-binding

The component created by React. createClass. this of each of its member functions is automatically bound to the React. You can use this. method directly at any time. this in the function will be correctly set.

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

For a Component created by React. Component, its member functions are not automatically bound to this and must be manually bound by the developer. Otherwise, this cannot obtain 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, React. component has three manual binding methods: It can be bound in the constructor, or it can be used in the call. bind (this) to complete the binding, you can also use the arrow function to bind. In the handleClick function of the preceding example, the binding can be:

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

<Div onClick = {this. handleClick. bind (this)}> </div> // bind to bind

<Div onClick = {() => this. handleClick ()}> </div> // bind with arrow function

The configuration of the component property type propTypes and its default props property defaultProps is different

React. createClass when creating a component, the property type of the props component and the default property of the component will beComponent instance attributesDefaultProps is to use the getdefaproprops method to obtain the default component attributes.

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

React. ComponentComponent class attributesIt is not the attribute of the component instance, that is, the so-calledStatic attributes of a class. The configuration above is as follows:

Class TodoItem extends React. component {static propTypes = {// static attribute name of the class: React. propTypes. string}; static defaultProps = {// class static property name :''};...}

The configuration of the component's initial state is different.

The state of a component created by React. createClass is configured by using the getInitialState method;

The state of a Component created by React. Component is declared in the constructor as if the Component property was initialized.

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> }}

Mixins support different

Mixins () is an implementation of Object-Oriented Programming (OOP). It is used to reuse common code and extract common code into an object, then, you can use Mixins to input the object for code reuse.

When creating a component, React. createClass can use the mixins attribute to mix a set of classes in the form of arrays.

var SomeMixin = {  doSomething() { }};const Contacts = React.createClass({  mixins: [SomeMixin], handleClick() { this.doSomething(); // use mixin }, render() { return ( <div onClick={this.handleClick}></div> ); }});

But unfortunately, React. component does not support Mixins. So far, the React team has not provided an official solution for this form. However, the React developer community provides a brand new way to replace Mixins, that isHigher-Order Components.

How to choose which method to create a component

The React team has declared that React. createClass will eventually be replaced by the React. Component class form. However, the React. createClass format will not be discarded until the Mixins alternative is found. Therefore:

Components created using React. Component do not need to be created using React. createClass.

In addition, the form of component creation should also be determined according to the following:

1. Use the stateless component creation mode whenever possible.

2. Otherwise (for example, the state, lifecycle method, and ref are required), use the es6 form of 'react. component' to create a Component.

The above is all the content of this article. I hope this article will help you in your study or work. I also hope to provide more support to the customer's home!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.