Reactコンポーネント
軽くReactチュートリアルをやってみた後に、TypeScriptで書くとこんな感じかな?とまとめました。
コンポーネントがViewの基本単位で、それぞれRender時に読み込む情報のPropsと状態を保持するStateというプロパティをもっているようです。
Class Component
import React, { FormEvent } from 'react';
interface MyProps {
value: number;
}
interface MyStates {
yourName: string;
}
interface MyInputEvent extends React.FormEvent<HTMLInputElement> {
target: HTMLInputElement;
}
export default class MyComponent extends React.Component<MyProps, MyStates>{
constructor(props: MyProps) {
super(props);
this.state = {
yourName: ''
}
this.handleOnChange = this.handleOnChange.bind(this);
}
public handleOnChange(e: MyInputEvent) {
e.preventDefault();
this.setState({ yourName: e.target.value });
}
public render() {
return (
<div>
<div>
<input
onChange={e => this.handleOnChange(e)}
/>
</div>
<span>{this.state.yourName}</span>
</div>
)
}
}
TypeAnnotationsが効くので、PropsTypeを設定せず、そのままTypeScriptのエコシステムで書き続けられて便利です。
Eventは、一度interfaceで定義してあげたほうが良さそう。
Function Component
こんな感じかな
interface MyProps {
value: number;
}
function MyComponent(props: MyProps) {
return (
<div>
<span>{props.value}</span>
</div>
);
}
これらを組み合わせてViewを作っていけばいいみたいです。ふむふむ。