LoginSignup
0
0

More than 1 year has passed since last update.

TypescriptによるReactコンポーネントの書き方

Posted at

VSCodeの拡張機能をインストール

VSCodeの拡張機能から、「react」と検索すると、以下が候補に挙がってくるのでインストールする。
Reactのスニペットを使えるようになる。

  • ES7+ React/Redux/React-Native snippets
    image.png

Reactコンポーネントのひな型

tsxファイルを作成し、「rafce」と入力し、Enterを押すと、Reactコンポーネントのひな型が入力される。

import React from 'react'

const Sample = () => {
  return (
    <div>Sample</div>
  )
}

export default Sample

Typescriptによる、Propsの型を指定

import React from 'react'
 
+ type Props = {
+   id: string
+   name: string
+ }


- const Sample = () => {
+ const Sample = ({id, name}: Props) => {
  return (
    <div>Sample</div>
  )
}

export default Sample

VSCodeのユーザースニペット登録

「Ctrl + Shift + P」で、ユーザースニペットを選択する。
初回登録時は、ファイル名を聞かれるので、任意の名前を付ける。(globalなど)
ユーザースニペットに以下のように書いておくと、「Props」と打つと、型宣言のひな型が入力される。

"Props": {
  "prefix": "Props",
  "body": ["type Props = {", "\t$1", "}"]
}
0
0
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
0