如何将带有装饰器的 React 组件重写为纯函数?

How do I rewrite a react component with decorators as a pure function?

我正在使用 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 linting 规则的错误,是不是不可能同时满足这两个规则?

好的,所以问题出在 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);

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