React 不使用ES6

来源:互联网 发布:交换机端口介绍 编辑:程序博客网 时间:2024/05/21 19:30

React Without ES6

ES6语法创建组件

class Greeting extends React.Component {  render() {    return <h1>Hello, {this.props.name}</h1>;  }}

如果不用ES6语法,就需要用create-react-class模块创建

var createReactClass = require('create-react-class');var Greeting = createReactClass({  render: function() {    return <h1>Hello, {this.props.name}</h1>;  }});

声明默认props

ES6 class中把defaultProps定义为组件的一个属性

class Greeting extends React.Component {  // ...}Greeting.defaultProps = {  name: 'Mary'};

createReactClass()中则要定义getDefaultProps()

var Greeting = createReactClass({  getDefaultProps: function() {    return {      name: 'Mary'    };  render: function() {        return <h1>Hello, {this.props.name}</h1>;      }  },});

设置state初始值

ES6中在constructor中直接设置this.state

class Counter extends React.Component {  constructor(props) {    super(props);    this.state = {count: props.initialCount};  }  // ...}

createReactClass()中则要定义getInitialState()

var Counter = createReactClass({  getInitialState: function() {    return {count: this.props.initialCount};  },  // ...});

自动绑定

ES6中不会主动给实例绑定this,所以要显示绑定

class SayHello extends React.Component {  constructor(props) {    super(props);    this.state = {message: 'Hello!'};    // 这行很重要    this.handleClick = this.handleClick.bind(this);  }  handleClick() {    alert(this.state.message);  }  render() {    // Because `this.handleClick` is bound, we can use it as an event handler.    return (      <button onClick={this.handleClick}>        Say hello      </button>    );  }}

createReactClass()就不需要主动绑定了

var SayHello = createReactClass({  getInitialState: function() {    return {message: 'Hello!'};  },  handleClick: function() {    alert(this.state.message);  },  render: function() {    return (      <button onClick={this.handleClick}>        Say hello      </button>    );  }});

虽说ES6的方法更麻烦点,但是实际效果更好。可以通过ES6箭头函数的特性去写(箭头函数体内的this对象就是定义所在的对象,而不是使用时所在的对象,且不可改变)

class SayHello extends React.Component {  constructor(props) {    super(props);    this.state = {message: 'Hello!'};  }  // WARNING: 这个语法还在测试阶段!  handleClick = () => {    alert(this.state.message);  }  render() {    return (      <button onClick={this.handleClick}>        Say hello      </button>    );  }}

以上方法还属于测试阶段,为了安全使用,可以遵照以下几条建议:

  • 在constructor里绑定this
  • 箭头函数调用时onClick={(e) => this.handleClick(e)}
  • 还是使用createReactClass
原创粉丝点击