Webエンジニアの備忘録

およそ自己の作業メモとして残しております。

Reactjsのstate/propsの挙動を確認する極力シンプルなコード

以下の記事で紹介したサンプルコードです。 tak-taniguchi.hatenablog.com

概要

Reactのstate/propsの関係を簡潔に表すために書いてみました。 余計なコードをほとんど書いていないので、UIは見づらいですが動きがわかりやすいかと思います(笑)

  • 動作に成功すると、ブラウザの左上に「0」が表示されます。
  • 「0」をクリックすると数値が加算されていきます。

ファイル構成

─ /
 └index.html
 └bundle.js      // index.jsxをbabelifyして作ってください
 └index.jsx      // ソース本体

index.html

<!doctype html>

<head>
  <meta charset="utf-8">
  <title>react state/props sample</title>
</head>

<body>
  <div id="content"></div>
  <script src="./bundle.js"></script>
</body>

</html>

index.jsx

import React from 'react'
import ReactDom, { render } from 'react-dom'

/**
 * 親コンポーネントクラス
 */
var Parent = React.createClass({
  getInitialState: function () {
    // this.state.counterを初期化しています
    return {
      counter: 0
    }
  },
  handleAdd: function () {
    // this.state.counterを加算するハンドラーです
    this.setState({
      counter: this.state.counter + 1
    });
  },
  render: function () {
    // 子コンポーネントを呼び出しています。
    return (
      <Child counter={this.state.counter} onClickHandler={this.handleAdd} />
    );
  }
});

/**
 * 子コンポーネントクラス
 */
var Child = React.createClass({
  render: function () {
    // this.props.onClickHandlerは親クラスhandleAdd()を参照
    // this.props.counterは親クラスのstate.counterを参照
    // onClick()が実行されると親クラスのstate.counterが加算されるため、子クラスのthis.props.counterも表示が変わる
    return (
      <div onClick={this.props.onClickHandler}>{this.props.counter}</div>
    );
  }
});

render(
  <Parent />,
  $('#content')[0]
);