かずきのBlog@hatena

すきな言語は C# + XAML の組み合わせ。Azure Functions も好き。最近は Go 言語勉強中。日本マイクロソフトで働いていますが、ここに書いていることは個人的なメモなので会社の公式見解ではありません。

Visual Studio上のTypeScript JSXを使ってReact.js「デフォルトのプロパティ」

JSXとかだとgetDefaultPropsというメソッドを定義しておくとプロパティのデフォルト値として使ってくれるんですがTypeScriptの場合違うらしい。

どうやるかというと、デフォルト値がほしいプロパティの定義に?をつけて必須じゃなくしてから、public static defaultPropsという感じのstaticなプロパティを定義するという感じでやるみたいです。こんな感じ。

/// <reference path="typings/tsd.d.ts" />

interface ToggleComponentProperties {
    text?: string;
}

interface ToggleComponentState {
    visible: boolean;
}

class ToggleComponent extends React.Component<ToggleComponentProperties, ToggleComponentState> {
    public static defaultProps: ToggleComponentProperties = { text: "Default!!" }

    constructor(props: ToggleComponentProperties) {
        super(props);
        this.state = { visible: true } as ToggleComponentState;
    }

    handleClick(): boolean {
        this.setState({ visible: !this.state.visible } as ToggleComponentState);
        return false;
    }

    render() {
        var header = <h1 className='header'>{this.props.text}</h1>;
        var button = <button onClick={this.handleClick.bind(this) }>Toggle!</button>;

        if (this.state.visible) {
            return <section>
                    {header}
                    {button}
                </section>;
        }

        return <section>{button}</section>;
    }
}

ReactDOM.render(
    <ToggleComponent />,
    document.getElementById('content'));