2016-11-04 58 views
0

假設我有以下反應代碼。React組件如何觸發兄弟React組件的功能

<Navigation parentWindow={this} /> 
<p>Sub Pages</p> 
<ReactCSSTransitionGroup 
    component="div" 
    transitionName="page-transition" 
    transitionEnterTimeout={0} 
    transitionLeaveTimeout={500} 
    > 
     {React.cloneElement(this.props.children, { 
      key: location.pathname 
     })} 
    </ReactCSSTransitionGroup> 

ReactCSSTransitionGroup將最終渲染的是由ContactPage.js創建一個<ContactPage />。下面是ContactPage.js樣子:

import React from 'react'; 

export default class Page extends React.Component 
{ 
    testMe() {alert('Hello World!');} 
    render() {return <div>Hello</div>;} 
} 

從我<Navigation />這是由Navigation.js創建的,我希望能夠觸發ContactPage.testMe()。所以,我做這在我的Navigation.js

import React from 'react'; 

export default class Page extends React.Component 
{ 
    render() { 
     this.props.parentWindow.props.children.testMe(); 
     return <div>Navigate me</div>; 
    } 
} 

但是當我運行該項目,我的導航給我的錯誤:

Uncaught TypeError: this.props.parentWindow.props.children.testCall 

我該如何解決這個問題得到什麼?

+0

你有導出默認的類頁面擴展你的Navigation.js中的React.Component。這只是一個複製和粘貼錯誤? – user5325596

回答

1

理論上你可以通過使用refs來實現。在ParentWindow組件中,您將爲克隆的子項分配一個ref,然後您將作爲道具傳遞給導航。

React的工作方式與其他JS庫有所不同,它會強制您將業務邏輯或事件邏輯移至父組件並將其作爲道具傳遞。我會建議你將一個回調函數傳遞給導航頁面,當觸發它時調用ContactPage方法。

class Navigation extends React.Component { 
    render() { 
    this.props.onAlertParent(); 
    return <div>Navigate me</div>; 
    } 
} 

class ParentWindow extends Component { 
    alertChild() { 
    if (this.childNode && this.childNode.testMe) { 
     this.childNode.testMe(); 
    } 
    } 

    render() { 
    <div> 
     <Navigation onAlertParent={() => this.alertChild()} /> 
     <p>Sub Pages</p> 
     <ReactCSSTransitionGroup 
     component="div" 
     transitionName="page-transition" 
     transitionEnterTimeout={0} 
     transitionLeaveTimeout={500} 
     > 
     {React.cloneElement(this.props.children, { 
      key: location.pathname, 
      ref: (node) => { this.childNode = node; } 
     })} 
     </ReactCSSTransitionGroup> 
    </div> 
    } 
} 

注意如何Navigation組件通過道具接收一個回調函數,導航元素並不需要知道它的兄弟姐妹什麼,那就是使用父傳達給他們。

反應方式是通過傳遞數據或回調來使用道具在組件之間進行通信。總是有一種比調用元素方法更好的溝通方式。即使我提出的方法是有缺陷,因爲它仍然調用元素的方法。

相關問題