2016-05-16 6 views
9

TypeScriptでReactを使用しており、ステートレス関数を作成しました。私はこの例から無用なコードを削除して読みやすくしています。TypeScriptに反応する - ステートレス関数でdefaultPropsを定義する

interface CenterBoxProps extends React.Props<CenterBoxProps> { 
    minHeight?: number; 
} 

export const CenterBox = (props: CenterBoxProps) => { 
    const minHeight = props.minHeight || 250; 
    const style = { 
     minHeight: minHeight 
    }; 
    return <div style={style}>Example div</div>; 
}; 

すべてが素晴らしいですし、このコードは正しく動作しています。しかし、私の質問があります:CenterBoxコンポーネントのためにdefaultPropsをどう定義することができますか?

それはreact docsに記載されているとおり:

(...) They are pure functional transforms of their input, with zero boilerplate. However, you may still specify .propTypes and .defaultProps by setting them as properties on the function, just as you would set them on an ES6 class. (...)

それはのように簡単にする必要があります:

CenterBox.defaultProps = { 
    minHeight: 250 
} 

しかし、このコードはTSLintエラーを生成します。error TS2339: Property 'defaultProps' does not exist on type '(props: CenterBoxProps) => Element'.

だから、再び:どのように正確に私はでき上記のスタック(React + TypeScript)にdefaultPropsを定義しますか?

答えて

10

解決策を探して2時間後に... それは働いています

あなたがdeufaultPropsあなたの関数定義行を定義したい場合はすべきでは次のようになります。React.SFCReact.StatelessComponentの別名であることを

CenterBox.defaultProps = { someProp: true } 

注:

export const CenterBox: React.SFC<CenterBoxProps> = props => { 
    (...) 
}; 

次に、あなたのような小道具を定義することができます。

この質問(および回答)が誰かを助けることを願っています。最新のReact入力がインストールされていることを確認してください。

+2

defaultPropsの仕組みに関する具体的な例を追加できますか?ありがとう –

2

これは、他の人がこれに遭遇した場合のステートフル機能のためにどのように機能するかです。 キーは、defaultPropsを静的変数として宣言しています。

interface IBoxProps extends React.Props<IBoxProps> { 
    x?: number; 
    y?: number; 
    height?: number; 
    width?: number; 
} 

interface IBoxState { 
    visible?: boolean; 
} 

export default class DrawBox extends React.Component<IBoxProps, IBoxState> { 
    static defaultProps: IBoxProps; 

    constructor(props: IBoxProps) { 
     super(props); 
    } 
    ... 
} 

DrawBox.defaultProps = { 
    x=0; 
    y=0; 
    height=10; 
    weight=10; 
}; 
関連する問題