Reactで属性(props)を扱う
最終更新日:2018-07-13
コンポーネント利用時に属性を設定させることができます。
属性オブジェクトの定義を書く
TypeScriptなので、属性オブジェクトがどのようなプロパティを持っているかの定義が必要です。ここではファイル名を属性として持たせてみます。
// App.tsx
interface IProps {
  fileName: string;
}
型引数とコンストラクタを追加する
属性はコンポーネントのコンストラクタで受け取ります。型の指定は `React.Component` の1つ目の型引数で指定します。
class App extends React.Component<IProps, any> {
  constructor(props: IProps) {
    super(props);
  }
  // 中略
}
属性を使用する
this.props` フィールドで属性にアクセスできます。
public render() {
  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <h1 className="App-title">Welcome to React</h1>
      </header>
      <p className="App-intro">
        To get started, edit <code>src/{this.props.fileName}</code> and save to reload.
      </p>
    </div>
  );
}
属性値を指定する
最後にコンポーネントを使う側です。 `IProps` で指定したフィールド名がそのまま属性名になります。
// index.tsx
ReactDOM.render(
  <App fileName="App.tsx"/>,
  document.getElementById('root') as HTMLElement
);
    
