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