かずきのBlog@hatena

すきな言語は C# + XAML の組み合わせ。Azure Functions も好き。最近は Go 言語勉強中。日本マイクロソフトで働いていますが、ここに書いていることは個人的なメモなので会社の公式見解ではありません。

Visual Studio上のTypeScript JSXを使ってReact.js「createFactory」

同じ名前のタグを沢山組み立てるときに楽ができるReact.createFactoryという関数があるみたい。こんな感じで、liタグを沢山作るときにあらかじめliタグを作るファクトリを定義することができる。

/// <reference path="typings/tsd.d.ts" />

var h1 = React.createElement('h1', { className: 'header' }, 'React!!');
var liFactory = React.createFactory('li');
var items =
    [
        liFactory({ className: 'item' }, 'item1'),
        liFactory({ className: 'item' }, 'item2'),
        liFactory({ className: 'item' }, 'item3'),
        liFactory({ className: 'item' }, 'item4')
    ];
var ul = React.createElement('ul', { className: 'list' }, items);

var section = React.createElement('section', { className: 'container' }, h1, ul);

ReactDOM.render(section, document.getElementById('content'));

これで、こんな感じのHTMLが生成された。

<section class="container" data-reactid=".0">
  <h1 class="header" data-reactid=".0.0">React!!</h1>
  <ul class="list" data-reactid=".0.1">
    <li class="item" data-reactid=".0.1.0">item1</li>
    <li class="item" data-reactid=".0.1.1">item2</li>
    <li class="item" data-reactid=".0.1.2">item3</li>
    <li class="item" data-reactid=".0.1.3">item4</li>
  </ul>
</section>