LoginSignup
8
8

More than 5 years have passed since last update.

TypeScriptでReactを書く(2):子コンポーネントを使う

Posted at

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は入力補完してくれないっぽい。辛い。

8
8
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
8
8