LoginSignup
0
0

More than 3 years have passed since last update.

[React] 関数コンポーネント

Last updated at Posted at 2020-08-08

関数コンポーネントとは

UIの一部を部品としてコンポーネント化することで、再利用できるようになる。
例えば、テキストを引数によって変更できるボタンをコンポーネント化する、のような感じである。

コード

今回はボタンコンポーネントを作成してみる。
まずはファイルを作成する。名前は適当に「Button.tsx」とする。

Button.tsx

import React from "react";

//他のファイルでこのファイルをimportすることで、ここの関数を使えるようになる
export default Button; 

//この関数を呼ぶことでボタンが返却される
function Button() {
  return <button>テストボタン</button>;
}

上記の関数を他のファイルで呼び出すときは以下のように書く。

App.tsx

import React from "react";
import { RecoilRoot } from "recoil";

//「Button」という名前でButton.tsxをimportする。名前は好きに付けることができる。
//fromの後はButton.tsxへのパスを書く。今回はApp.tsxと同じ階層にあるので以下のようにしている。
import Button from "./Button";

// import文で付けた名前のタグで関数コンポーネントを呼び出せる
function App() {
  return (
    <RecoilRoot>
      <div>
        <Button></Button> 
      </div>
    </RecoilRoot>
  );
}

export default App;

表示結果

ボタンが表示される
スクリーンショット (110).png

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