Three ways to summarize React components and best practices

Source: Internet
Author: User



React focus on the view layer, the component is the basis of the React, but also one of its core concepts, a complete application will be assembled by a separate component.



Up to now, React has been updated to v15.4.2, due to the popularity of ES6 and the impact of different business scenarios, we will find that there are currently three ways to create React components:1. ES5 notation react.createclass,2. ES6 notation react.component,3. A stateless functional notation (pure component-sfc).



What kind of writing do you love best? Turnip Greens each their own ~ Each team has its own code specification and development model, but the writing of React components will be to improve code reading, better component performance, easy bug tracking as the principle. Let's talk about the differences between these three ways of writing and the best practices for each scenario.


es5-notation React.createclass


React.createclass Needless to say, we first used this method to build a component "class", which takes an object as a parameter, the object must declare a render method,render returns a component instance, the following with a Examples of Switchbutton components look at the specific use of React.createclass:


 1 var React = require(‘react‘);
 2 var ReactDOM = require(‘react-dom‘);
 3 
 4 var SwitchButton = React.createClass({
 5   getDefaultProp:function() {
 6     return { open: false }
 7   },
 8 
 9   getInitialState: function() {
10     return { open: this.props.open };
11   },
12 
13   handleClick: function(event) {
14     this.setState({ open: !this.state.open });
15   },
16 
17   render: function() {
18     var open = this.state.open,
19       className = open ? ‘switch-button open‘ : ‘btn-switch‘;
20 
21     return (
22       <label className={className} onClick={this.handleClick.bind(this)}>
23         <input type="checkbox" checked={open}/>
24       </label>
25     );
26   }
27 });
28 
29 ReactDOM.render(
30   <SwitchButton />,
31   document.getElementById(‘app‘)
32 );
es6-notation React.component


React upgrade to v0.13 support the ES6 class syntax, we can use the class App extends react.component{...} Way to create components, which is also the official recommended way to create stateful components. An example of rewriting the above Switchbutton components with ES6:


1 import React from ‘react‘
 2 import { render } from ‘react-dom‘
 3 
 4 class SwitchButton extends React.Component {
 5   constructor(props) {
 6     super(props)
 7     this.state = {
 8       open: this.props.open
 9     }
10     this.handleClick = this.handleClick.bind(this)
11   }
12 
13   handleClick(event) {
14     this.setState({ open: !this.state.open })
15   }
16 
17   render() {
18     let open = this.state.open,
19       className = open ? ‘switch-button open‘ : ‘btn-switch‘
20 
21     return (
22       <label className={className} onClick={this.handleClick}>
23         <input type="checkbox" checked={open}/>
24       </label>
25     )
26   }
27 }
28 
29 SwitchButton.defaultProps = {
30   open: false
31 }
32 
33 render(
34   <SwitchButton />,
35   document.getElementById(‘app‘)
36 )



The difference between creating a component with React.createclass:



Import
instead of importing the module with an import statement using ES6 here , import {render} can import the variable name directly from the module, which is more concise and intuitive.






Initialize State
When React uses ES6 's "class" Inheritance implementation, the getinitialstate hook function is removed, and thestate's initialization is declared in the constructor method constructor.



This binding
React.component the event function does not automatically bind this when creating a component, we need to bind it manually, otherwise this will not point to the instance object of the current component. There are three ways to bind this:






1. Hard binding using bind () in constructor


constructor() {
  this.handleClick = this.handleClick.bind(this);
}


2. Use bind () binding directly on the element


<label Classname={classname} onclick={this.handleclick.bind (this)}>


3. ES6 has a very useful syntactic sugar: arrow function, which makes it easy to point this directly to class Switchbutton (which is equivalent to the familiar var self = This, but the latter makes the code confusing, and Arrow Function solves the problem very well.


<label Classname={classname} onclick={() =>this.handleclick ()}>
Stateless functional notation (pure component SFC)


Both React.createclass and react.component can be used to create stateful components, while stateless components -stateless Component are React after v0.14.



It arises because as the complexity of the application increases and the number of components is increased, the components are divided into different types according to their respective responsibilities, so there is a pure component which is only responsible for the display, which is characterized by the need not to manage state , the data passed directly through the props, which also conforms to React The idea of unidirectional data flow.






For this stateless component, declaring it in a functional way makes the code more readable and significantly reduces the amount of code, and Arrow function is the best partner for functional notation:


1 const Todo = (props) => (
2   <li
3     onClick={props.onClick}
4     style={{textDecoration: props.complete ? "line-through" : "none"}}
5   >
6     {props.text}
7   </li>
8 )


The Todo component defined above, the input and output data is determined entirely by props, and does not produce any side effects. For props as Object type, we can also use ES6 's deconstruction assignment:


1 const Todo = ({ onClick, complete, text, ...props }) => (
2   <li
3     onClick={onClick}
4     style={{textDecoration: complete ? "line-through" : "none"}}
5     {...props}
6   >
7     {props.text}
8   </li>
9 )


Stateless components are typically used with high-level components (for short: OHC), and higher-order components are used to host the State,redux framework to manage data sources and all States through the store, where all components responsible for presentation use stateless function notation.



This model is encouraged to split the original large component as simple as possible in a larger project, and future React will also have some special optimizations for this stateless component, such as avoiding meaningless checks or memory allocations. Therefore, it is recommended that you use stateless components in your project whenever possible.



Of course, a stateless component is not a balm, such as it does not support "ref" because it is simple because the component is not instantiated before React calls it, and naturally there is no "ref", (ref and Finddomnode actually breaks the convention between parent and child components passing the state only through props, which violates the React principle and needs to be avoided.


Comparison of the above three formulations and best practices


Facebook officials have long stated that ES6react.component will replace React.createclass. As React continues to evolve,React.createclass exposes a number of problems:


    • React.createclass automatically binds functions, which can result in unnecessary performance overhead, compared to the functions required by react.component for selective binding.
    • React.createclass Biological mixin,react.component no longer support, in fact mixin not elegant and intuitive, the alternative is to use more popular high-order components-HOC, If your project is still inseparable, you can use React-mixin


In general: The stateless function style is better than React.createclass, and React.createclass is better than react.component.



Resources:



Three ways to create React components and best practices



React three ways to create components and their differences



React high-order components



Summarize three ways and best practices for React components


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.