2017-07-25 43 views
0

使用React [15.6.1] Redux [3.7.2]和路由器[4.1.1] 我嘗試訪問屬於其他(同級)組件的方法,但似乎無法能夠訪問它們。 反正有出口這些方法嗎?React訪問同級組件方法

   ---------- 
       ¦ Parent ¦ 
       ---------- 
        ¦ 
    ------------------------------- 
    ¦    ¦    ¦ 
----------- ----------- ----------- 
¦ Child 1 ¦ ¦ Child 2 ¦ ¦ Child 3 ¦ 
----------- ----------- ----------- 


// Child 1 has a method submitChild1() 
// Child 2 has a method submitChild2() 
// Child 3 has to access both of those methods 


class Parent1 extends React.Component { 

    render() { 
     return (
      <div> 
       <Child1 /> 
       <Child2 /> 
       <Child3 /> 
      </div> 
     ); 
    } 

} 

class Child1 extends React.Component { 

    submitChild1() { 
     dispatch(Action1()); 
    } 

    render() {...} 

} 

class Child2 extends React.Component { 

    submitChild2() { 
     dispatch(Action2()); 
    } 

    render() {...} 

} 

class Child3 extends React.Component { 

    submitTheOtherMethods() { 
     // try to access Child 1 method 
     // try to access Child 2 method 
    } 

    render() {...} 

} 

回答

1

您不能這樣做,您將違背React設計目的,這有助於確保組件設計良好且不與其他人緊密耦合。

如果您希望在多個不同組件之間共享方法,則需要在父級上定義方法,並將這些方法作爲屬性傳遞給子組件。

如果您需要在其中一個方法中調用方法,則生命週期掛鉤仍然可以訪問組件屬性。

+0

嗨馬丁, 基本上Child1和Child2是搜索表單,Child3是一種分頁,我想觸發這些操作,取決於哪種形式是可見的,因爲他們已經調度到商店的正確行動。 – Kup

+0

將組件連接在一起並不是一個好設計。有幾種方法可以實現。由於您使用的是'redux',因此您應該知道正在顯示哪個頁面,並使用通用分頁操作相應地進行分頁。我不知道你是否在使用'redux-thunk','redux-saga'或其他的東西,但這隻需要你的動作產生或者適當的修改。 –

+0

好的,我會研究一下。乾杯 – Kup