TypeScriptとReactでコンポーネントを作るメモ。TypeScriptもES6もimport/export周りの理解があやふやなので使い方間違ってるかもしれない。動くには動く。
PropとかStateとか、Reactの仕組み的なものは一人React.js Advent Calendar 2014が非常に参考になる。Prop = 定数かと思ってたけど、Prop = そのコンポーネントでは書きかえられない(= 親コンポーネントから書きかえられることはある)ということか。
実装
子コンポーネント。export default
(=module.export)でクラスをexportする。
countText.tsx
/// <reference path="../../../typings/bundle.d.ts" />
import * as React from 'react';
export default class CountText extends React.Component<any, any> {
constructor(props) {
super(props);
}
render() {
return (
<div>{ this.props.message } { this.props.count }</div>
);
}
}
親コンポーネント。import
で使えるようになる。
Hello.tsx
/// <reference path="../../../typings/bundle.d.ts" />
import * as React from 'react';
import CountText from './countText';
class Hello extends React.Component<any, any> {
constructor(props) {
super(props);
this.state = {
count: 0
}
}
onClick() {
this.setState({ count: this.state.count + 1});
}
render() {
return (
<div>
<CountText message="count: " count={this.state.count}></CountText>
<button onClick={ this.onClick.bind(this) }>UP!</button>
</div>
);
}
}
React.render(<Hello />, document.getElementById('app'));
もはやTypeScriptでもなんでもない。これからしっかり型を書いていきます...
でも手元のエディタ(atom)だと.tsx
は入力補完してくれないっぽい。辛い。