LoginSignup
4
3

More than 5 years have passed since last update.

Reactのes7記法でthisをbindせずに動かす

Last updated at Posted at 2016-02-04

reactのes7に挑戦中のタカシです。es7は美しさの代償としてあらゆるmethodsにthisをbindせざるおえなくなりました。たとえばこんな風に

class Counter extends React.Component {
  constructor() {
    super();
    this.tick = this.tick.bind(this);
  }
  tick() {
    ...
  }
  ...
}

もう少し美しくかけないかと模索していたところ、公式にそのまま載ってました。こんな感じです。

  tick = () => {
    alert(this.state.name)
  };

これで動きます。thisをbindせずとも。ただし注意してください。最後のセミコロンは必須です。

まだまだ謎多きes7の世界。去年まではちょっと便利な書き方ができる程度に考えてましたが、jsを新しい言語へと昇華させる試みのように思えます。自由すぎたjsにある種の秩序をもたらしてくれることを期待しています。

参考:https://facebook.github.io/react/blog/2015/01/27/react-v0.13.0-beta-1.html#autobinding

4
3
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
4
3