LoginSignup
0
2

More than 3 years have passed since last update.

ReactをTypeScriptで入門する on May, 2019

Last updated at Posted at 2019-06-04

Reactコンポーネント

軽くReactチュートリアルをやってみた後に、TypeScriptで書くとこんな感じかな?とまとめました。
コンポーネントがViewの基本単位で、それぞれRender時に読み込む情報のPropsと状態を保持するStateというプロパティをもっているようです。

Class Component

import React, { FormEvent } from 'react';

interface MyProps {
  value: number;
}
interface MyStates {
  yourName: string;
}
interface MyInputEvent extends React.FormEvent<HTMLInputElement> {
  target: HTMLInputElement;
}

export default class MyComponent extends React.Component<MyProps, MyStates>{
  constructor(props: MyProps) {
    super(props);
    this.state = {
      yourName: ''
    }
    this.handleOnChange = this.handleOnChange.bind(this);
  }
  public handleOnChange(e: MyInputEvent) {
    e.preventDefault();
    this.setState({ yourName: e.target.value });
  }
  public render() {
    return (
      <div>
        <div>
          <input
            onChange={e => this.handleOnChange(e)}
          />
        </div>
        <span>{this.state.yourName}</span>
      </div>
    )
  }
}

TypeAnnotationsが効くので、PropsTypeを設定せず、そのままTypeScriptのエコシステムで書き続けられて便利です。
Eventは、一度interfaceで定義してあげたほうが良さそう。

Function Component

こんな感じかな

interface MyProps {
    value: number;
}
function MyComponent(props: MyProps) {
  return (
    <div>
      <span>{props.value}</span>
    </div>
  );
}

これらを組み合わせてViewを作っていけばいいみたいです。ふむふむ。

参考文献

0
2
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
0
2