LoginSignup
7
5

More than 3 years have passed since last update.

React with typescript入門-Reactの型定義-

Last updated at Posted at 2020-09-26

はじめに

どうもシュータです。
React.jsを使用する際、より堅牢なプログラムの作成やパフォーマンス、リーダブル性などの観点から型定義が行われることがしばしばありますが
型定義の選択肢の一つとしてaltjsであるtypescriptの採用が挙げられます。

今回はtypescriptでReact.jsのコンポーネントを書く方法を簡単にまとめていきます。

Functional Component

まず、typescriptを使用せずにReactの関数コンポーネントを定義します。

import React from 'react'; 

function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

//アロー関数バージョン

const Welcome = (props) => <h1>Hello, {props.name}</h1>;

これをtypescriptで書くとこうなります。
Propsに型定義を加えました。


import React from 'react'; 

type Props = {
  name : string
}

function Welcome(props : Props) {
  return <h1>Hello, {props.name}</h1>;
}

//アロー関数バージョン

const Welcome = (props : Props) => <h1>Hello, {props.name}</h1>;

さらにtypescriptのGenerics(ジェネリクス)を使用して次のように書くこともできます。

import React, { FunctionComponent } from 'react';

type Props = {
  name : string
}

const Welcome: FunctionComponent<Props> = (props) => <h1>Hello, {props.name}</h1>;

//下記も同様です。

const Welcome: React.FC<Props> = (props) => <h1>Hello, {props.name}</h1>;

ちなみにReact.SFCというのもあるのですが
現在はdeprecatedのようです。

class component

こちらもまず、typescriptを使用せずにクラスコンポーネントを定義します。


import React from 'react'; 

class Welcome extends React.Component {
  render(){
    return <h1>Hello, {this.props.name}</h1>;
  }
}

上記をtypescriptを使用して書くと次のようになります。


import React from 'react'; 

interface Props {
  name: string,
}
interface State {}

class Welcome extends React.Component<Props,State> {
  render(){
    return <h1>Hello, {this.props.name}</h1>;
  }
}

stateに値を入れる場合はinterface State {}で設定し、constructorにも型を加えます。


import React from 'react'; 

interface State {
  name : string
}

class Welcome extends React.Component<{},State> {
 constructor(props: State) {
    super(props);
    this.state = {
      name : "hoge"
    };
  }

  render(){
    return <h1>Hello, {this.state.name}</h1>;
  }
}

終わりに

ざっくりとReact.jsの関数コンポーネントとクラスコンポーネントを
typescriptで記述する方法をまとめました。

propsにデフォルトの値を設定する書き方や
optionalのpropsを設定する書き方もありますが
状況によってカスタマイズして使っていくと良いと思います。

reference

https://reactjs.org/docs/components-and-props.html
https://fettblog.eu/typescript-react/components/
https://fettblog.eu/typescript-react-component-patterns/
https://tech.pjin.jp/blog/2017/09/20/react-primer-component/
https://qiita.com/alfe_below/items/1cb81a6a03d8d6d73b27

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