2017-03-22 232 views
0

任何想法,如果有一個乾淨的解決方案,這個「paradoxon」?兒童訪問父組件

class Container extends Component { 
    render() { 
     <Parent> // ---------v 
      <Child parent={Parent} /> // Reference to "Parent" 
     </Parent> 
    } 
} 

的問題是,當然,<Child><Parent>之前呈現

最終目標是能夠從<Child>內調用<Parent>的實例方法。

我已經嘗試過解決方法,如(ref),回調函數(getParentReference()),可以將其作爲使用cloneElement()甚至this._reactInternalInstance新的道具通過基準,但沒有人似乎(被極度哈克開)工作。

+0

您可以傳遞方法作爲參數。例如'' – Abhishek

+0

如果你真的想這樣做,把必要的方法作爲prop傳遞給孩子。 – dfsq

+0

@Abhishek,@dfsq:方法是_within_' '... – kraftwer1

回答

0

你應該考慮使用回調函數。

回調函數

的父母會傳遞一個函數給孩子做道具,像這樣:

<MyChild myFunc={this.handleChildFunc.bind(this)} /> 

而且孩子會調用該函數,像這樣:

this.props.myFunc(); 

不要忘記,孩子需要在propTypes中聲明這個函數:

MyChild.propTypes = { 
    myFunc: React.PropTypes.func, 
}; 

欲瞭解更多信息,請閱讀8 no-Flux strategies for React component communication

+0

謝謝,但我想要傳遞的函數位於_within_''。沒有_this.handleChildFunc()_... – kraftwer1

+0

只需在'Parent'組件中定義'handleChildFunc',然後將它作爲prop傳遞給'MyChild'組件,如示例中所示。好像你誤解了這個概念。 :) – dschu

+0

我已更新我的代碼片段以更好地說明我的問題。請注意,我並沒有試圖從'Container'(你提供的例子中)添加一個道具,而是從我的''組件(它不是''')'。 – kraftwer1