LoginSignup
8
8

More than 5 years have passed since last update.

TypeScriptでReactを書く(3):propTypes

Posted at

propTypesやdefaultPropsの設定に少しハマったのでメモ。
公式ドキュメントにはES6 classでの方法が書いてあるが、TypeScriptだとそのまま持ってきても「そんなプロパティはそのクラスには無い」と怒られる。
https://facebook.github.io/react/docs/reusable-components.html

メンバにしてstaticを付けたら出来た。付けないとフロントで実行時にwarnが出る。でもこのやり方も正攻法かわからないので詳しい方教えてください。

サンプルはToDoリストアプリに使おうと思ってる、ただの入力フォーム。入力完了イベントを親コンポーネントに投げるため、propを定義、親からメソッドを渡してもらいそれを実行する。

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

import * as React from 'react';

export default class TaskInputForm extends React.Component<any, any> {

  static propTypes: Object = {
    added: React.PropTypes.func.isRequired
  };

  constructor(props) {
    super(props);

    this.state = {
      text: ""
    };
  }

  onClick() {
    this.props.added(this.state.text);
  }

  onChange(e) {
    this.setState({text: e.target.value});
  }

  render() {
    return (
      <div>
        <textarea value={ this.state.text } onChange={ this.onChange.bind(this) }></textarea>
        <button onClick={ this.onClick.bind(this) }>作成</button>
      </div>
    );
  }
}
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