es6+ Developing React Components

Source: Internet
Author: User
Tags es6 class

Here's a brief look at the implications of these new language features for the development of React applications, which make React development simpler and more interesting.

Class

So far, the best embodiment of our use of es6+ to write React components is that we chose to use the class definition syntax. Instead of using the React.createclass method to define a component, we can define a bonafide ES6 class to extend the React.component:

?
12345 classPhoto extends React.Component {  render() {    returnthis.props.caption} src={this.props.src} />;  }}

Now you'll find a subtle difference--when using a definition class, the syntax is more concise:

?
12345 // The ES5 wayvarPhoto = React.createClass({  handleDoubleTap: function(e) { … },  render: function() { … },});
?
12345 // The ES6+ wayclassPhoto extendsReact.Component {  handleDoubleTap(e) { … }  render() { … }}

It is worth noting that we have removed two parentheses and a semicolon, and each method declares that we omit a colon, a keyword, and a semicolon.

When using the new class definition, at least one of all life-cycle methods is in line with your expectations. The constructor of the class now assumes that the role was previously populated by Componentwillmount:

?
1234 // The ES5 wayvarEmbedModal = React.createClass({  componentWillMount: function() { … },});
?
1234567 // The ES6+ wayclassEmbedModal extendsReact.Component {  constructor(props) {    super(props);    // Operations usually carried out in componentWillMount go here  }}
Property Initialization Program

In the world of the es6+ class, prop types and Defaults live in the class itself as a static property. These, as well as the initialization state of the component, can be defined using the ES7 property initializers :

?
1234567891011121314151617181920 // The ES5 wayvarVideo = React.createClass({  getDefaultProps: function() {    return{      autoPlay: false,      maxLoops: 10,    };  },  getInitialState: function() {    return{      loopsRemaining: this.props.maxLoops,    };  },  propTypes: {    autoPlay: React.PropTypes.bool.isRequired,    maxLoops: React.PropTypes.number.isRequired,    posterFrameSrc: React.PropTypes.string.isRequired,    videoSrc: React.PropTypes.string.isRequired,  },});
?
12345678910111213141516 // The ES6+ wayclassVideo extendsReact.Component {  staticdefaultProps = {    autoPlay: false,    maxLoops: 10,  }  staticpropTypes = {    autoPlay: React.PropTypes.bool.isRequired,    maxLoops: React.PropTypes.number.isRequired,    posterFrameSrc: React.PropTypes.string.isRequired,    videoSrc: React.PropTypes.string.isRequired,  }  state = {    loopsRemaining: this.props.maxLoops,  }}

The ES7 property initializer action Constructor,this the inner class to the construction class instance, so the initialization state can depend on This.props. It is worth noting that we no longer define prop defaults and use Getter functions to initialize State objects.

Arrow function

The React.createclass method is used to perform some additional binding work in your component instance method, in order to ensure that the this keyword points to the component instance:

?
1234567 // autobinding,  Brought to you by react.createclass var  postinfo = react.createclass ({    Code class= "JS plain" >HANDLEOPTIONSBUTTONCLICK:  function (e)  {      //  Here,  ' This '  refers to the component instance.      this .setstate ({showoptionsmodal:  true    });

Since we do not participate in the React.createclass method, but instead use the es6+ class syntax to define the component, it appears that you need to bind the instance method manually:

?
123456789101112 // Manually bind, wherever you need toclassPostInfo extendsReact.Component {  constructor(props) {    super(props);    // Manually bind this method to the component instance...    this.handleOptionsButtonClick = this.handleOptionsButtonClick.bind(this);  }  handleOptionsButtonClick(e) {    // ...to ensure that ‘this‘ refers to the component instance here.    this.setState({showOptionsModal: true});  }}

Fortunately, by binding two es6+ attributes – arrow functions and the property initializer – you can choose to bind the component instance:

?
12345 classPostInfo extendsReact.Component {  handleOptionsButtonClick = (e) => {    this.setState({showOptionsModal: true});  }}

ES6 's Arrow function body shares the same word this, using this to surround their code, which can achieve the results we expect, and also the way the ES7 property initializes the program within the domain. Peek under the hood to see why it can be achieved.

Dynamic Property name & template string

One of the object constant enhancements is the name that can be assigned to a derived property. We may initially set some states like this:

?
1234567 var  form = react.createclass ({    ONCHANGE:  function (inputname, e)  {      var  statetoset = {};      STATETOSET[INPUTNAME +  ' Value ' ] = e.target.value;      this .setstate (statetoset);    });

Now we have the ability to construct an object that determines the property name through a run-time JavaScript expression. Here, we use a template string to determine which property sets the state:

?
1234567 classForm extendsReact.Component {  onChange(inputName, e) {    this.setState({      [`${inputName}Value`]: e.target.value,    });  }}
Deconstruction & Propagation Properties

Often when writing components, we may want to pass the props of most parent components to subcomponents, but not all. Combined with es6+ deconstruction and JSX propagation Properties , this does not require an extra part to achieve:

?
1234567891011121314 class AutoloadingPostsGrid extends React.Component {  render() {    var {      className,      ...others,  // contains all properties of this.props except for className    } = this.props;    return (      <div className={className}>        <PostsGrid {...others} />        <button onClick={this.handleLoadMoreClick}>Load more</button>      </div>    );  }}

We can combine JSX propagation properties and general properties to implement overrides and defaults with a simple precedence principle. This element will require className "override" or even this.props existence ClassName attribute:

?
123 <div {...this.props} className="override">   … </div>

This element normally requires className "base" unless This.props has ClassName property overrides:

?
123 <div className="base"{...this.props}>   … </div>

I hope you can enjoy the es6+ language features to React development brought some convenience.

es6+ Developing 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.