LoginSignup
19
4

More than 5 years have passed since last update.

react、typescriptでStateless Functional Component の書き方をググった

Last updated at Posted at 2018-12-01

react、typescript初心者です。

react、typescriptのチュートリアルを見ると、基本的にclass Componentでのやり方が多く、Stateless Functional Component(以下SFC)ではどう書くのか気になったのでググってみました。

react/typescriptの環境は @toshi-toma さんの ReactのプロジェクトにTypeScriptを導入する〜npm installからコンパイルまで〜 を参考にさせていただきました!

コードはこちら

動作環境作成

$ yarn init --yes
$ yarn add -D webpack webpack-cli typescript ts-loader react react-dom @types/{react,react-dom}
tsconfig.json
{
    "compilerOptions": {
        "noImplicitAny": true,
        "module": "ES2015",
        "target": "es5",
        "jsx": "react"
    }
}
webpack.config.js
module.exports = {
    mode: "development",
    entry: "./src/index",
    output: {
        path: __dirname + "/dist",
        filename: "bundle.js",
    },
    module: {
        rules: [
            {
                test: /\.tsx?$/,
                loader: ["ts-loader"],
            },
        ],
    },
    resolve: {
        extensions: [".ts", ".tsx", ".js"]
    },
};

サンプル1 interfaceを使った場合

import * as React from "react";

interface IProps {
    foo: string;
}

export default (props: IProps) => (
    <h1>{props.foo}</h1>
);

サンプル2 type aliasを使った場合

import * as React from "react";

type Props = {
    foo: string;
}

export default (props: Props) => (
    <h1>{props.foo}</h1>
);

サンプル3 React.SFC

import * as React from "react";

interface IProps {
    foo: string;
}

const App: React.SFC<IProps> = props => (
    <h1>{props.foo}</h1>
);

export default App;

試してみましたが、asを使えば React.SFCの場合でもexport default の部分でかけるようです。(間違ってたらごめんなさい)

import * as React from "react";

interface IProps {
    foo: string;
}

export default (
    props => (
        <h1>{props.foo}</h1>
    )
) as React.SFC<IProps>;

追記

SFC より FC を使ったほうが良さそうです。コメント参考

@suzu2469 さんコメントありがとうございます!

最後まで見ていただいてありがとうございました。


参考


19
4
1

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
19
4