LoginSignup
9
11

More than 5 years have passed since last update.

Reactのクラスメソッドをarrow関数で書きたい時

Posted at

概要

reactでクラスでコンポーネントを作成するときにクラスメソッドをarrow関数で書けるとbindとか省略できて楽ですよね。でも@babel/preset-envと@babel/preset-reactだけでバンドルするとエラーが発生してしまいます。
調べてみたら@babel/plugin-proposal-class-propertiesをインストールしてbabelの設定に組み込むと使えるそうなので紹介したいと思います。
ちなみにこのサイトを参考にしています。リンク先ではbabel-plugin-transform-class-propertiesを使ってますが@babel/plugin-proposal-class-propertiesが最新らしいのでこちらで記述した例で説明しています。

やりたいこと

Reactでボタンをアクションを行いたいとき以下のようにコンポーネントを書きます。

test.jsx
class Test extends React.Component {

  handle() {
    console.log('test')
  }

  render() {
    return (
      <Button onClick={this.handle.bind(this)}>Test</Button>
    );
  }
}

または、constructorにbindをひとまとめにして以下のようにすることもできます。

test.jsx
class Test extends React.Component {
  constructor(props){
    super(props);
    this.handle = this.handle.bind(this);
  }
  ...
}

ボタン一つとかならこれでもいいんですけど複数コールバックができてくるとつけ忘れたり削除忘れたりコード量が増えたり面倒臭いです。

ここでES2015で追加されたarrow関数はthisをデフォルトで引き継いでいるのでこのbindを省略して以下のように書くことができるだろうと思って

test_arrow.jsx
class Test extends React.Component {

  handle = () => {
    console.log('test')
  }

  render() {
    return (
      <Button onClick={this.handle}>Test</Button>
    );
  }
}

npmで以下をインストールして

npm install --save-dev @babel/preset-env @babel/preset-react babel-loader

webpack.config.jsのpresetsを以下のように記述して

webpack.config.js
{
    presets: [[
        "@babel/preset-env", {
            "useBuiltIns": "entry",
            "targets": {
                "esmodules": true
            }
        }],
        "@babel/preset-react"
    ]
}

バンドルすると以下のようなエラーが出てしまします。

SyntaxError: test_arrow.js: Support for the experimental syntax 'classProperties' isn't currently enabled :

これを解消できるのが@babel/plugin-proposal-class-propertiesになります。

手順

  • @babel/plugin-proposal-class-propertiesをインストールする
  • webpackのloaderの設定を行う

まずはnpmで@babel/plugin-proposal-class-propertiesをインストールします。

npm install --save-dev @babel/plugin-proposal-class-properties

webpack.config.jsのmoduleで以下のようにloaderに追加します

webpack.config.js
{
    presets: [[
        "@babel/preset-env", {
            "useBuiltIns": "entry",
            "targets": {
                "esmodules": true
            }
        }],
        "@babel/preset-react"],
    plugins: [
        '@babel/plugin-proposal-class-properties',
    ],
}

この設定でバンドルすることにより先ほどのエラーはなくなりarrow関数でクラスメソッドを書けるようになります

まとめ

@babel/plugin-proposal-class-propertiesを使うことでクラスメソッドをarrow関数で書くことができるようになりました。
ちなみにarrow関数ではない関数とも併用して使うこともできます。

おまけ

ちなみに元記事によるとこの@babel/plugin-proposal-class-propertiesはarrow関数をクラスメソッドで使えるようになるだけではなく以下のような機能も使えるようにしてくれます

クラスの中にPropsTypeを書ける

sample.jsx
class Test extends React.Component {
  static propTypes = {
    message: React.PropTypes.string
  }
}

スプレッド演算子でcomponentに値を渡せる

sample2.jsx
class Warning extends React.Component {
  static propTypes = {
    message: React.PropTypes.shape({
      title: React.PropTypes.string,
      text: React.PropTypes.string
    })
  }
render() {
    return (
      <Message
        {...this.props.message}
        type="error"
      />
    );
  }
}

英語は苦手なので詳しいことは読めてないですが参考までに

9
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
11