我正在使用airbnb eslint设置,其设置为a rule that enforces stateless react components to be rewritten as a pure function。以下组件触发了此规则,这意味着下面的组件最好编写为纯函数:

import React from 'react';
import { observer } from 'mobx-react';
import cssmodules from 'react-css-modules';

import styles from './index.css';
import Select from '../Select/';
import List from '../List/';

@cssmodules(styles)
@observer
export default class Analysis extends React.Component {
  render() {
    return (
      <div styleName="wrapper">
        <div styleName="column">
          <Select store={this.props.store} />
        </div>
        <div styleName="column">
          <List store={this.props.store} />
        </div>
      </div>
    );
  }
}

Analysis.propTypes = {
  store: React.PropTypes.object.isRequired,
};

但是,当我将其重写为纯函数(见下文)时,出现错误Leading decorators must be attached to a class declaration:
import React from 'react';
import { observer } from 'mobx-react';
import cssmodules from 'react-css-modules';

import styles from './index.css';
import Select from '../Select/';
import List from '../List/';

@cssmodules(styles)
@observer
function Analysis(props) {
  return (
    <div styleName="wrapper">
      <div styleName="column">
        <Select store={props.store} />
      </div>
      <div styleName="column">
        <List store={props.store} />
      </div>
    </div>
  );
}

Analysis.propTypes = {
  store: React.PropTypes.object.isRequired,
};

那么我可以将其编写为纯组件并仍然附加装饰器吗?还是这是Airbnb掉毛规则中的错误,并且不可能同时满足这两个规则吗?

最佳答案

好的,所以问题出在es7风格的装饰器上。对它们进行除糖可以解决问题:

import React from 'react';
import { observer } from 'mobx-react';
import cssmodules from 'react-css-modules';

import styles from './index.css';
import Select from '../Select/';
import List from '../List/';

function Analysis(props) {
  return (
    <div styleName="wrapper">
      <div styleName="column">
        <Select store={props.store} />
      </div>
      <div styleName="column">
        <List store={props.store} />
      </div>
    </div>
  );
}

Analysis.propTypes = {
  store: React.PropTypes.object.isRequired,
};

export default cssmodules(observer(Analysis), styles);

它虽然不漂亮,但确实有效,并且不会触发任何错误。

09-15 13:46