2014-08-30 134 views
0

我試圖劫持全局方法中的所有按鈕處理程序,並在滿足某些條件時手動觸發處理程序。這裏一個簡單的例子:http://jsfiddle.net/zvy80mpf/劫持React處理函數

var clickHandler = function(e) { 
    console.log(e.target); // Button 
    // I want to hijack the component handler here and trigger it manually 
} 

var Hello = React.createClass({ 
    handler: function() { 
     console.log('component onclick'); 
    }, 
    render: function() { 
     return (
      <div onClick={this.props.clickHandler}> 
       <button handler={this.handler}>Hello</button> 
      </div> 
     ); 
    } 
}); 

React.renderComponent(<Hello clickHandler={clickHandler} />, document.body); 

我知道我可以通過handler功能,但我想從全球範圍內訪問處理程序,而無需修改內部組件。

在jQuery中,你可以使用$._data(element, 'events')來做到這一點,在React中有沒有類似的方法?

回答

-1

,如果你綁定你gobal處理程序,以「本」在你的組件,你應該能夠從全局函數調用組件的點擊處理程序,就像這樣:

var clickHandler = function(e) { 
    console.log(e.target); // Button 
    // Hijack the component onClick here 
    this.handler(); 
} 

var Hello = React.createClass({ 
    handler: function() { 
     console.log('component onclick'); 
    }, 
    render: function() { 
     return (
      <div onClick={this.props.clickHandler.bind(this)}> 
       <button handler={this.onClick}>Hello</button> 
      </div> 
     ); 
    } 
}); 

React.renderComponent(<Hello clickHandler={clickHandler} />, document.body); 
1

我不知道到完全理解你所要求的,但...

在React中有一種未公開的方式將數據傳遞給子組件的整個層次結構。

您可以爲例使用以下命令:

React.withContext({handler: handler},function() { 
     React.renderComponent(
      self.mountComponent(props), 
      self.mountNode 
     ); 
    }); 

然後你就可以用一個mixin訪問處理程序中的所有子組件,如:

var WithHandlerMixin = { 
    contextTypes: { 
     handler: React.PropTypes.func.isRequired 
    }, 
    getHandler(): function() { 
     return this.context.handler; 
    } 
}; 

這是未公開的,因爲它被認爲是不穩定由React團隊提供,可能有一些bug。但根據我的經驗,使用像這樣的簡單代碼工作良好,已經被一些流行的React框架使用,如Fluxxor,沒有任何問題。請注意簽名可能會改變,但React團隊告訴我該功能不會被刪除。

然而,你必須修改所有訪問該處理程序的組件,但mixin並不是那麼幹擾我猜。

+0

有趣。我更喜歡基於DOM節點(或對組件的引用)訪問處理程序,但這種方式也可能工作 – David 2014-09-01 19:38:26