2017-05-06 96 views
1

我想創建一個基類,將其包裝在一個容器中,然後在我的其他組件中進行擴展。反應打字稿擴展容器

下面是一個簡單的例子:

let state = new State(); 
class Base extends React.Component<{}, {}> { 

} 

const Container = state.connect(
    () => { 
     return { 

     } 
    }, 
    () => { 
     return { 

     } 
    } 
)(Base); 

class S extends Container { 

} 

然而,這是返回一個錯誤:

`error TS2507: Type 'any' is not a constructor function type.`. 

如果我直接延長Base,它工作正常,但後來我怎麼會得到訪問狀態併發送我放入容器的操作?

UPDATE

我創建了以下接口(略去模板爲簡單起見)

interface IState { 
    connect: (
     mapStateToProps:() => any, 
     mapDispatchToProps:() => any, 
    ) => (component: typeof React.Component) => typeof React.Component 
} 

let state: IState = new State(); 

現在類擴展不會引發任何錯誤。但是,原來的Base類永遠不會被調用!只調用Connect方法的構造函數。

這裏的想法是,我將有一個抽象的組件和容器(所有的調度動作都在容器上)。然後我可以從其他類中擴展這個組件。但是,由於容器包含所有調度操作,因此我需要擴展容器,而不是組件。

+0

也許你應該申報HOC特殊類型:看這裏:http://stackoverflow.com/questions/41499831/type-annotation-for-react-higher-order-component-using-typescript –

+0

超過在同一天的3個問題:) –

回答

0

我想你可以重複使用state.connect()返回的值。

let state = new State(); 
class Base extends React.Component<{}, {}> { 
} 

class S extends Base { 
} 

const containerFactory = state.connect(
    () => { 
     return {} 
    }, 
    () => { 
     return {} 
    } 
); 

const BaseContainer = containerFactory(Base); 
const SContainer = containerFactory(S); 
+0

是的,我可以做到這一點,但我想用它作爲'S類擴展BaseContainer'。原因是因爲我使用的是Typescript,所以我需要訪問BaseContainer的道具 – Kousha