未経験からのReact入門『TypeScript』|JSX
概要
React では JSX(JavaScriptXML)と呼ばれる変数の宣言方法を推奨しています。
JSX はタグ構文を変数に格納できるようにした JavaScript の拡張構文です。
具体的には以下のように記述します。
const element = <h1>Hello, world!</h1>;
そして JSX を使用しない場合の方法が以下の通りです。
const element = React.createElement('h1', {}, 'Hello, world!');
どちらの方が可読性において優れているか一目瞭然かと思います。
React では JSX を使用する方法が推奨されているので、積極的に使っていきましょう。
実際に使ってハローワールドの出力
実際に JSX を使って出力してみます。
前回作成したプロジェクトの index.tsx を編集します。
// index.tsx
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
const element = <h1>Hello, world!</h1>;
ReactDOM.render(
<React.StrictMode>
element
<App />
</React.StrictMode>,
document.getElementById('root')
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();
関数を使った出力
JSX を使うことで、数式や関数の出力を簡単に簡単に行うことができます。
const element = <h1>{1 + 1}</h1>
const element = <h1>func(param)</h1>
例として、TypeScript を使って型定義をした関数の実行を行い、Hello World を出力してみます。
以下のコードを確認してください。
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
const element = <h1>Hello, world!</h1>;
ReactDOM.render(
<React.StrictMode>
element
<App />
</React.StrictMode>,
document.getElementById('root')
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();
TypeScript でできることを使ってコードを記載してみました。
まずはクラス作成です。TypeScript ではクラスを作成し、型判定に使用できます。
class Massage {
first: string;
last: string;
constructor(first:string,last:string) {
this.first = first;
this.last = last;
}
}
今回は Massage クラスをを作成し、コンストラクターで値を設定できるようにします。
const massage = new Massage("Hello", "World");
次に Massage クラスを引数に受け取り Message クラスのデータを変形し、string 型を返す関数を作成しています。
内容は Massage クラスの first オブジェクトを last オブジェクトを連結しているだけなので、非常にシンプルかと思います。
function formatMassage(massage: Massage): string {
return massage.first + ' ' + massage.last;
}
JSX では{}で囲むことで、JavaScript のオブジェクトにアクセスすることができます。
今回は、formatMassage を呼び出すように設定します。
const element = <h1>{formatMassage(massage)}</h1>;
まとめ
JSX は React を使う上では絶対に使った方がいい技術なのでぜひ覚えておきたいですね。