ReactJS小记(3)

By | 2016/02/24

我又来标题党了,最近感觉,使用ReactJS都是高手,太基础的东西好像多说也没意思了,今天还是来点(湿嗒嗒的)干货吧!

ES6是JavaScript的未来(其实已经到来了),有了很多新的语法(糖?),给我们编码带来了不少方便,随意还是与时俱进用ES6和Webpack创造新的世界吧。对了顺便说一下,ES2015就是ES6,而ES7应该算ES2016?

ReactJS中Component用ES6的Class应该怎么写呢?

// 普通的写法
var Hello = React.createClass({
  getDefaultProps: function() {
    return {name: "Default Props"};
  },

  render: function() {
    return <div>Hello {this.props.name}</div>;
  }
});
// ES6的写法
class Hello extends React.Component {
  constructor(props) {
    super(props); // 只有调用过super后才能使用this
    this.state = {name: this.props.initialName}; // 直接给state赋值,代替getInitialState()
  }

  render() {
    return <div>Hello {this.state.name}</div>;
  }
}
Hello.defaultProps = {initialName: "Default Props"};

 ES7中更厉害,直接作为属性写就行,不过实在太新了,暂时还是不写了避免混淆。

ES6的Component怎么用Mixin呢?

文档说了,ES6的语法暂时不支持Mixin,不过我们有张良计,虽然麻烦了一点~

import React from 'react/addons';
import ReactMixin from 'react-mixin';

export default class Signup extends React.Component {

  render() {
  }
}

ReactMixin(Signup.prototype, React.addons.LinkedStateMixin);

 

Category: Web

发表评论

您的电子邮箱地址不会被公开。