2016-06-15 3 views
6

高次コンポーネント内のコンポーネントからPropTypeを作成した場所を指す方法がありますか?高次コンポーネントのPropTypes

enter image description here

これは小さなサンプルですが、別々のファイルで、アプリケーション全体EnhancedButtons複数あった場合、これは、デバッグには非常に難しいだろう。

高位コンポーネントは理想的には再利用性のために作られているため、handleClickメソッドが見つからないコンポーネントの場所を知ることはできません。 _EnhancedButtonのレンダリングメソッドは、拡張する必要があるComponentの変数です。

FinalButtonが挿入されていて、_EnhancedButtonのインスタンスであり、prop handleClickClickが欠けているなど、PropTypesを作成している場所をより明白にする方法はありますか?あなたの例では

https://jsfiddle.net/kriscoulson/sh2b8vys/3/

var Button = (props) => (
 
\t <button onClick={() => props.handleClick() }> 
 
\t \t Submit 
 
\t </button> 
 
); 
 

 
Button.propTypes = { 
 
\t handleClick: React.PropTypes.func.isRequired 
 
} 
 

 
const EnhanceButton = Component => class _EnhancedButton extends React.Component { 
 
\t render() { 
 
    \t return (<Component { ...this.props }>{this.props.children}</Component>); 
 
    } 
 
} 
 

 
const FinalButton = EnhanceButton(Button); 
 

 
ReactDOM.render(
 
    <FinalButton />, 
 
    document.getElementById('container') 
 
);
<script src="https://facebook.github.io/react/js/jsfiddle-integration-babel.js"></script> 
 

 
<div id="container"> 
 
    <!-- This element's contents will be replaced with your component. --> 
 
</div>

答えて

16

FinalButtonは、それはちょうどあなたのローカル変数の名前であるので、反応することが知られることはありませんが、我々はその結果得られるコンポーネントの名前を変更しますあなたが望むものなら、なんでも。ここでは、元の名前が何であっても、 "Final"を使用します。

また、小包の種類を新しい要素にコピー/マージすることもできます。

function EnhanceButton(Component) { 
    class _EnhancedButton extends React.Component { 
     static displayName = 'Final' + (Component.displayName || Component.name || 'Component'); 

     render() { 
      return (
       <Component { ...this.props }>{this.props.children}</Component> 
      ); 
     } 
    } 
    _EnhancedButton.propTypes = Component.propTypes; 

    return _EnhancedButton; 
} 

これは与える:警告:失敗propType:Buttonに指定されていなかった小道具​​必要です。レンダリング方法がFinalButtonであることを確認します。

フィドル:https://jsfiddle.net/luggage66/qawhfLqb/

+0

ありがとうございます! :) – Mihir

4

荷物の答えは、おそらくクリーナー、別の、非常にうまく動作しますが、代替は静的としてあなたproptypesを宣言し、部品の体内にそれらを宣言することです。

const EnhanceButton = Component => class extends React.Component { 
    static propTypes = { 
    children: PropTypes.node, 
    } 
    static defaultProps = { 
    children: false, 
    } 
    render() { 
    return (
     <Component 
     { ...this.props } 
     > 
     {this.props.children} 
     </Component> 
    ); 
    } 
} 
関連する問題