41
39

More than 5 years have passed since last update.

React.js + ES6 で超簡単なサンプルを作った

Posted at

React.js 最近良く名前を見るので始めた。

React.js v0.13RC では,ECMAScript6風のclass文などに対応したので,ES6の構文を使った簡単なサンプルを作成.

作成したサンプル

Count Up!ボタンを押すと上の数値が増えるだけ
counter.gif

作成したファイルは2つだけ

  • index.html
  • app.jsx

index.html

  • React.js本体と、JSX変換スクリプトを読み込む
  • ES6風記述を有効にするためにtype="text/jsx;harmony=true"とする
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title></title>
    <!-- React.js, JSX変換, アプリの3つを読み込む -->
    <script src="http://fb.me/react-0.13.0-rc1.min.js"></script>
    <script src="http://fb.me/JSXTransformer-0.13.0-rc1.js"></script>
    <script src="app.jsx" type="text/jsx;harmony=true"></script>
</head>
<body>

<div id="app-container"></div>

</body>
</html>

app.jsx

  • ES6のclass構文を利用してComponentを作る
  • 状態はすべてthis.stateに閉じ込める。変更するときは直接ではなく、this.setStateを使う
  • onClickなどのDOMイベントからメソッドを呼び出すときは最後に.bind(this)をつける
class Counter extends React.Component {
    constructor() {
        this.state = {
            count: 0
        };
    }

    onClick() {
        this.setState({
            count: this.state.count + 1
        });
    }

    render() {
        return (
            <div>
                <h1>{this.state.count}</h1>
                <button onClick={this.onClick.bind(this)}>Count Up!</button>
            </div>
        )
    }
}

React.render(
    <Counter />,
    document.getElementById('app-container')
);
41
39
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
41
39