Autobinding, React 和 ES6 中的 class (译)

883 阅读1分钟

原文链接
在网站 Ticket Arena 从React 0.12 到0.13的变迁中包含了很多ES6为JavaScript带来的新特性。我们一直在用BabelWebpack来尽可能确保在使用更多新特性的情况下维护浏览器的兼容性。

尤其,我们在使用class来写React组件时会是这样:

import React from 'react';
let {Component, PropTypes} = React;
export default class MyComponent extends Component 
{
  // lifecycle methods and statics
  ... 
  // render actual DOM output
  render() {
    return 
; } } MyComponent.propTypes = { foo: PropTypes.bool.isRequired}

我们在前边几个版本的React中所依赖的几个已经移除的特性中,尤其是Mixin, 还有一些相对不明显的,自动绑定。

使用React.createClass自动绑定

在以往,你在eventListener中使用this.handler时React会魔法般的为这个handler绑定当前对象的this,this.handler === this.handler.bind(this)。然而,在变迁到ES6的类中后这个特性被移除了,还好我们有一个超级简单的变通方案,箭头函数!

你可以在ReactClass的源码来看看Facebook的详细实现。

箭头函数

箭头函数并不会定义他们自己的this值,取而代之的是当前上下文的this。因此(x) => this.y * x 可以等价于 function(x) { return this.y * x }.bind(this)

我们在React中怎么去使用它呢?好吧,这是一个小问题, ES6在类的定义中不允许这样初始化属性的(foo = 'bar';)。然而,可以通过Babel来支持,只需要如下设置即可"optional": ["es7.classProperties"]

接下来就可以这样来重写前边的一段代码,我们可以模拟auto-binding:

import React from 'react';
let {Component, PropTypes} = React;
export default class MyComponent extends Component
{
// lifecycle methods and statics
  static propTypes = { foo: PropTypes.bool.isRequired }
  handler = (e) => { ... } // render actual DOM output
  render() {
    return 
; } }

你可以在React官方博客 上查看更多相关信息。