这个类声明中使用的Javascript形式是什么?

时间:2016-09-22 08:22:17

标签: javascript node.js reactjs react-jsx

这是来自React-toolbox的table example(可以使用标签)

class TableTest extends React.Component {
  state = { selected: [], source: users };

  handleSelect = (selected) => {
    this.setState({selected});
  };

  render () {
    return (
      <Table
        model={UserModel}
        onSelect={this.handleSelect}
        selectable
        multiSelectable
        selected={this.state.selected}
        source={this.state.source}
      />
    );
  }
}

这不能用webpack / babel为我编译,但以下'正确'的Javascript确实如此。这是JSX表示法,并且表明我没有像我想的那样转发JSX吗?

class TableTest extends React.Component {
  constructor() {
    super();
    this.state = { selected: [], source: users };

    this.handleSelect = (selected) => {
      this.setState({selected});
    };
  }

  render () {
    return (
      <Table
        model={UserModel}
        onSelect={this.handleSelect}
        selectable
        multiSelectable
        selected={this.state.selected}
        source={this.state.source} />
    );
  }  
}

Webpack / babel窒息:

ERROR in ./src/client/app/app.jsx
Module build failed: SyntaxError: Unexpected token (21:8)

  19 | 
  20 | class TableTest extends React.Component {
> 21 |   state = { selected: [], source: users };

2 个答案:

答案 0 :(得分:1)

这是使用class properties,目前是Babel stage 2 preset的一部分。

对于此代码,类主体中的=语句将通过类属性转换移动到构造函数中。

Here's the original code in the Babel REPL with suitable presets applied

您需要将此预设(或较低阶段预设,因为所有Babel舞台预设还包括更高阶段功能)添加到您的Babel配置中,或单独添加转换插件。

示例Babel配置,它将提供转换原始代码所需的所有功能:

{
  presets: ['es2015', 'react', 'stage-2']
}

答案 1 :(得分:-1)

它在类中的=声明中抛出错误。由于React没有自动绑定规则,您需要将this绑定到handleSelect

https://facebook.github.io/react/docs/reusable-components.html#no-autobinding

class TableTest extends React.Component {
  constructor(props) {
      super(props);
      this.state = {
        selected: [], source: users
      };
      this.handleSelect = this.handleSelect.bind(this);
  }

  handleSelect(selected) {
    this.setState({selected});
  }

  render () {
    return (
      <Table
        model={UserModel}
        onSelect={this.handleSelect}
        selectable
        multiSelectable
        selected={this.state.selected}
        source={this.state.source}
      />
    );
  }
}