React component writing Summary

Source: Internet
Author: User
Tags es6 class

React component writing Summary

React focuses on the view layer. componentization is the basis of React and one of its core concepts. A complete application will be assembled by independent components.

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 statement React. createClass, 2. ES6 statement React. component, 3. stateless functional writing (pure component-SFC ).

Which of the following statements do you like most? Radish and vegetables each have their own love ~ Each team has its own code specification and development model. However, when writing React components, the principle is to improve code readability, better component performance, and easy bug tracking. Next, let's talk about the differences between the three writing methods and the best practices for their respective application scenarios.

ES5-React. createClass

React. createClass is needless to say. We first use this method to construct a component "class". It accepts an object as a parameter. An object must declare a render method, and render returns a component instance, the following uses a SwitchButton component as an example to look at React. the specific usage of createClass:

var React = require('react');var ReactDOM = require('react-dom');var SwitchButton = React.createClass({ getDefaultProp:function() { return { open: false } }, getInitialState: function() { return { open: this.props.open }; }, handleClick: function(event) { this.setState({ open: !this.state.open }); }, render: function() { var open = this.state.open,  className = open ? 'switch-button open' : 'btn-switch'; return (  <label className={className} onClick={this.handleClick.bind(this)}>  <input type="checkbox" checked={open}/>  </label> ); }});ReactDOM.render( <SwitchButton />, document.getElementById('app'));

ES6-React. Component

After the React is upgraded to v0.13, The ES6 class syntax is supported. We can use the class App extends React. component {...} to create a component, which is currently officially recommended to create a stateful component. Example of using ES6 to override the SwitchButton component above:

import React from 'react'import { render } from 'react-dom'class SwitchButton extends React.Component { constructor(props) { super(props) this.state = {  open: this.props.open } this.handleClick = this.handleClick.bind(this) } handleClick(event) { this.setState({ open: !this.state.open }) } render() { let open = this.state.open,  className = open ? 'switch-button open' : 'btn-switch' return (  <label className={className} onClick={this.handleClick}>  <input type="checkbox" checked={open}/>  </label> ) }}SwitchButton.defaultProps = { open: false}render( <SwitchButton />, document.getElementById('app'))

Different from creating a component using React. createClass:

Import

The ES6 import Statement is used to replace the require () method import module. The import {render} can directly import the variable name from the module, which is more concise and intuitive.

Initialize state

The getInitialState hook function is removed when React uses ES6's "class" to inherit the implementation. state Initialization is declared in constructor, the constructor method of the constructor.

This binding

When React. Component creates a Component, the event function does not automatically bind this. We need to manually bind this, otherwise this will not point to the Instance Object of the current Component. There are three methods to bind this:

1. Use bind () in constructor for hard binding

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

2. bind () binding directly on the element

<label className={className} onClick={this.handleClick.bind(this)}>

3. ES6 has a useful syntax SUGAR:Arrow Function (Arrow Function) can easily direct this to class SwitchButton (its Function is equivalent to the familiar var self = this, but the latter will make the code messy, the Arrow Function can solve this problem well)

<label className={className} onClick={()=>this.handleClick()}>

Stateless function writing (pure component SFC)

Both React. createClass and React. Component can be used to create stateful components, while Stateless Component, a Stateless Component, was launched after v0.14.

The reason is that, as the application complexity increases and the number of components increases, components are divided into different types based on their respective responsibilities. Therefore, a pure component is only responsible for display, it features no need to manage state, and data is passed in directly through props, which also conforms to the React one-way data stream idea.

For this stateless component, the use of functional Declaration will make the code more readable and greatly reduce the amount of code. Arrow Function is the best partner for functional writing:

const Todo = (props) => ( <li onClick={props.onClick} style={{textDecoration: props.complete ? "line-through" : "none"}} > {props.text} </li>)

The input and output data of the Todo component defined above is completely determined by props and will not produce any side effects. When props is of the Object type, we can also use the deconstruct value assignment of ES6:

const Todo = ({ onClick, complete, text, ...props }) => ( <li onClick={onClick} style={{textDecoration: complete ? "line-through" : "none"}} {...props} > {props.text} </li>)

Stateless components are generally used together with high-level components (OHC) to host state. The Redux framework manages data sources and all States through store, all components that are responsible for display use the stateless function method.

This mode is encouraged to separate the original huge components in a large project in a simple way. In the future, React will also perform some special optimization for such stateless components, for example, avoid meaningless checks or memory allocation. Therefore, we recommend that you use stateless components in projects as much as possible.

Of course, stateless components are not gold. For example, they do not support "ref". The reason is very simple, because components will not be instantiated before React calls it, and naturally there will be no "ref ", (ref and findDOMNode actually break the rule that only States are transmitted through props between parent and child components. This violates the React principle and must be avoided ).

Comparison of the above three writing methods and best practices

Facebook has long declared that ES6React. Component will replace React. createClass. As React continues to develop, React. createClass exposes some problems:

  • Compared with React. Component, You can selectively bind the required functions. React. createClass automatically binds the functions, which leads to unnecessary performance overhead.
  • React. createClass's own mixin, React. component is no longer supported. In fact, mixin is not elegant and intuitive enough. The alternative solution is to use the more popular high-level Component-HOC. If your project is still inseparable, you can also use react-mixin.

In general, stateless function writing is better than React. createClass, while React. createClass is better than React. 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!

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.