2017-12-03 12 views
0

独立したステートレスコンポーネントのレンダリングメソッドからコンポーネントのロジックにアクセスできるようにします。別々のレンダリング間でコンポーネントロジックを反応させる

理由は、デスクトップ版のアプリでは同じロジックとクラスのメソッドを使用しますが、そのプレゼンテーションは異なるためです。

class Logic { 
    constructor() { 
    this.greeting = 'Buongiorno' 
    } 

    showCats() { 
    return 'Mittens and Puss' 
    } 
} 

const Desktop =() => { 
    return <div style={{ fontSize: 30 }}> 
    {this.showCats()} 
    {this.greeting} 
    </div> 
} 

const Mobile =() => { 
    return <div style={{ fontSize: 15 }}> 
    {this.greeting} 
    {this.showCats()} 
    </div> 
} 

私はクラスを機能コンポーネントに「接着」しようとしています。

ステートレスコンポーネントに小道具を渡すことなくこれを行うことはできますか?

Logicクラス内のステートレスコンポーネントはどのようにしてメソッドと変数にアクセスできますか?

私はLogicクラスをextendが、私はそれを行うための最善のことであることを確認していないDesktopMobileステートフルなコンポーネントを作ることができ承知しています。

+0

あなたをラップすることを「高次成分」アプローチを使用することによって解決することができます彼らに必要なロジックを提供するクラスのステートレスコンポーネント – Flying

+0

あなたはいつデスクトップ上で、いつ携帯電話であなたが知っているようですね?なぜLogicクラスのレンダー機能でこの情報を(条件として)使用しないのですか? –

+0

@Flyingより高次のコンポーネントを書くための良い出発点は何ですか? – alanbuchanan

答えて

1
function Logic(wrappedComponent) { 
     showCats() { 
     return 'Mittens and Puss' 
     } 
     return (
     <wrappedComponent 
     greetings="Buongiorno" 
     showCats=showCats 

     > 
     {this.props.children} 
     <wrappedComponent /> 
    ) 

    } 

    const Desktop =() => { 
     return <div style={{ fontSize: 30 }}> 
     {this.props.greeting} 
     {this.props.showCats()} 
     </div> 
    } 
    export default Logic(Desktop) 

    const Mobile =() => { 
     return <div style={{ fontSize: 15 }}> 
     {this.props.greeting} 
     {this.props.showCats()} 
     </div> 
    } 
    export default Logic(Mobile) 

高次成分は、一般的に「高次成分」アプローチを使用することによって解決され、このここhttps://medium.com/@franleplant/react-higher-order-components-in-depth-cf9032ee6c3e#.do3h4kouk

1

このタスクキャブについて複数の異なるcomponents.readの間で共通の機能を維持するために使用されています。あなたのHOCは次のようになります。

"use strict"; 
import React, {Component} from "react"; 

const getDisplayName = (Component) => Component.displayName || Component.name || 'Component'; 

/** 
* Higher order component to inject logic into provided component 
*/ 
export const withLogic = Component => { 
    class WithLogic extends Component { 
     //noinspection JSUnusedGlobalSymbols 
     static displayName = `WithLogic(${getDisplayName(Component)})`; 

     get logic() { 
      if (!this._logic) { 
       this._logic = new Logic(); 
      } 
      return this._logic; 
     } 

     render() { 
      return <Component {...this.props} />; 
     } 
    } 

    return WithLogic; 
}; 

およびその使用は広くで使用される構図パターンは、リアクトです:

export default withLogic(Mobile);