LoginSignup
8
7

More than 5 years have passed since last update.

TypescriptでReact.ComponentのデフォルトProps値を定義する

Posted at

はじめに

TypeScriptとReactJSを使ってReact.Componentを継承したクラスを定義する際、
Propsプロパティのデフォルト値を定義する必要が出てきたのですが、
React公式ページに掲載されいてる方法ではうまくかなったので、TypeScript用の定義方法をメモしておきます。

問題

Propsのデフォルト値をどのように指定するかを調べたところ、
Component Specs and Lifecycle#getDefaultProps()では以下のように書かれていました。

Invoked once and cached when the class is created. Values in the mapping will be set on this.props if that prop is not specified by the parent component (i.e. using an in check).

This method is invoked before any instances are created and thus cannot rely on this.props. In addition, be aware that any complex objects returned by getDefaultProps() will be shared across instances, not copied.

上記ページではメソッドgetDefaultPropsでデフォルト値を定義するようになっていたので、

import * as React from 'react';

interface SomeProps extends React.Props<{}> {
  prop1: string
}

class SomeComponent extends React.Component<SomeProps, {}> {
   ... 中略 ...

   getDefaultPros() {
      return {prop1: "default"};
   }

   ... 中略 ...
}

というように実装しましたが、実行時に

warning.js:44Warning: getDefaultProps was defined on SomeComponent, a plain JavaScript class. This is only supported for classes created using React.createClass. Use a static property to define defaultProps instead.

というメッセージが表示されてしまいました。

TypeScriptでの定義方法

上記のメッセージにも書かれていますが、TypeScriptでは以下のようにデフォルトProps値を定義します。

class SomeComponent extends React.Component<SomeProps, {}> {
    public static defaultProps: SomeProps = {prop1: "default"};
    ...
}

参考

How to declare class properties defaultProps?

8
7
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
8
7