未経験からのReact入門|コンポーネント
概要
React はコンポーネント単位でパーツを分けることが可能です。
コンポーネントは機能の塊みたいなもので、prosp と呼ばれるコンポーネントに渡す引数によって処理を変えることができます。
コンポーネントは大きく分けて関数コンポーネントとクラスコンポーネント二つの要素が存在します。
関数コンポーネント
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
クラスコンポーネント
class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
以上の二つは、それぞれ同じ出力を与えます。
上記の二つのコードは公式ドキュメントに掲載されているコードをそのままもってきましたが、これは JavaScript で書かれています。
これを TypeScript に書き直してみます。
関数コンポーネント
TypeScript で関数コンポーネントを作るとき、props インターフェースを自作しなければいけません。
なのであらかじめ props に入る値は何なのか決めます。
今回は Hello World を言う文字列なので、props インターフェースの name オブジェクトを string 型とします。
import React from 'react';
interface Props {
name: string;
}
function Welcome(props:Props) {
return <h1>{props.name}</h1>;
}
class Greeting extends React.Component {
render() {
return <Welcome name="helloworld"></Welcome>;
}
}
export default Greeting;
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import Greeting from './Greeeting';
import reportWebVitals from './reportWebVitals';
const element = <Greeting></Greeting>;
ReactDOM.render(
element,
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();
クラスコンポーネント
関数コンポーネント同様に、Props インタフェースは自作します。
作成した Props インターフェースは Component クラス継承時に設定するのを忘れないようにしましょう。
import React from 'react';
interface Props {
name: string;
}
class Greeting extends React.Component<Props> {
render() {
return <h1>{this.props.name}</h1>
}
}
export default Greeting;
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import Greeting from './Greeeting';
import reportWebVitals from './reportWebVitals';
const element = <Greeting name="hello world"></Greeting>;
ReactDOM.render(
element,
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 だと記述量が若干増えますが、Props の書き直しなどが発生せず、また異常な値が入れられた時などすぐにわかるようになります。