2017-04-18 64 views
0

裹組件功能,想象一下,通過onTouchStart檢測按鍵觸摸事件的觸摸行爲HOC。現在使用觸摸HOC的包裝組件將具有其自己的處理程序邏輯。我的HOC組件如何調用包裝組件處理函數?訪問從HOC

只是爲了得到一個想法,這就是我所需要的。在研究我發現this使用裁判調用目標組件。我想知道是否有更好的方法來實現這一點。

TouchBehavior HOC

const TouchBehavior = (WrappedComponent) => 

    class extends React.Component { 
     constructor(props) { 
      super(props); 
      this.state = { 
       active: false, 
      }; 
      this.handleAction = this.handleAction.bind(this); 
      this.setActiveState = this.setActiveState.bind(this); 
      this.resetActiveState = this.resetActiveState.bind(this); 
     } 

     handleAction(e) { 
      e.preventDefault(); 
      this.setActiveState(); 
      //call wrapped component specific handler logic here 
      _.delay(() => this.resetActiveState() , 150); 
     } 

     setActiveState() { 
      this.setState ({ 
       active: true 
      }); 
     } 

     resetActiveState() { 
      this.setState ({ 
       active: false 
      }); 
     } 

     render() { 
      let touchBehaviorProps = { 
       onTouchStart: this.handleAction 
      }; 
      return <WrappedComponent {...this.props} touchBehaviorProps={touchBehaviorProps} /> 
     } 
    }; 

裹組件

class Button extends React.Component { 

componentSpecificHandlerLogic(){ 
    //logic goes here 
} 

render() { 
    return <button {..this.props.touchBehaviorProps}></button> 
} 
} 
+0

,您可以發送觸摸狀態道具的組件。這將導致包裹組分反應到它想要的任何方式的觸摸狀態。此外,這將適用於無狀態組件。 – hazardous

回答

2

只要有可能,我會盡量不拉邏輯備份的樹,而是通過更多了。

可能有很多方法可以實現這一點,但一個選項,我在這種情況下看到的是改變提供給包裹組件的道具是與提供的定製邏輯構造處理他們的一個功能。

TouchBehavior HOC

const TouchBehavior = (WrappedComponent) => 

    class extends React.Component { 
     constructor(props) { 
      super(props); 
      this.state = { 
       active: false, 
      }; 
      this.handleAction = this.handleAction.bind(this); 
      this.setActiveState = this.setActiveState.bind(this); 
      this.resetActiveState = this.resetActiveState.bind(this); 
     } 

     handleAction(e, customHandler) { 
      e.preventDefault(); 
      this.setActiveState(); 
      customHandler(); 
      _.delay(() => this.resetActiveState() , 150); 
     } 

     setActiveState() { 
      this.setState ({ 
       active: true 
      }); 
     } 

     resetActiveState() { 
      this.setState ({ 
       active: false 
      }); 
     } 

     render() { 
      let touchBehaviorProps = (customHandler) => ({ 
       onTouchStart: (e) => this.handleAction(e, customHandler) 
      }); 
      return <WrappedComponent {...this.props} touchBehaviorProps={touchBehaviorProps} /> 
     } 
    }; 

裹組件,而不是調用回調

class Button extends React.Component { 

componentSpecificHandlerLogic(){ 
    //logic goes here 
} 

render() { 
    return <button {...this.props.touchBehaviorProps(componentSpecificHandlerLogic)}></button> 
} 
} 
+0

輝煌。完美的作品 – fsociety