2016-09-09 4 views
4

リアクションでは、必要なプロンプトと必要なタイプを指定できます。未知の小道具名(例えば、propTypeに指定されていないもの)がコンポーネントに渡されたときに検証警告を表示する可能性はありますか?高次の成分は何もして冗長プロペラ検証に反応する

+0

https://facebook.github.io/react/docs/reusable-components.html – Maxwelll

答えて

3

が可能です:

// This is not a full solution, merely a sketch of one way to do it 
const OnlyValidProps = WrappedComponent => { 
    return class extends React.Component { 
    render() { 
     const actualProps = Object.keys(this.props); 
     const expectedProps = Object.keys(WrappedComponent.propTypes); 
     const hasPropMisMatch = (
     actualProps.length != expectedProps.length || 
     !actualProps.every(key => expectedProps.contains(key)) 
    ); 
     if (hasPropMisMatch) { 
     console.warn(`Props mismatch! expected: ${expectedProps} actual: ${actualProps}`); 
     } 
     return <WrappedComponent {...this.props} />; 
    } 
    }; 
} 

// Usage 
OnlyValidProps(class MyClass extends React.Component { 
    static propTypes = { 
    x: React.PropTypes.number, 
    y: React.PropTypes.number 
    } 
}); 
+0

も仕事継承しませんか? –

+0

コンポーネントを 'render'で返す前にどのようなメソッドを呼び出すか覚えておく必要がありますが、確かにそうです。 –

+0

私は、チェックを行い、サブクラスがそのレンダリングメソッドからsuper.renderを呼び出す、基本クラスにrenderメソッドを持つことを意味しました。私は本当にどちらかの方法でメリットがあるかどうか疑問に思っていました。 –