【问题标题】:React typescript extending a container反应打字稿扩展容器
【发布时间】:2017-05-06 07:14:56
【问题描述】:

我正在尝试创建一个基类,将其包装在一个容器中,然后在我的其他组件中扩展它。

这是一个简化的例子:

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,它可以正常工作,但是我将如何访问状态并调度我放入容器中的操作?

更新

我创建了以下界面(为简单起见省略了模板)

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

let state: IState = new State();

现在类扩展不会抛出任何错误。然而,原来的Base 类永远不会被调用!只调用Connect方法的构造函数。

这里的想法是我将拥有一个抽象组件和容器(所有调度动作都在容器上)。然后我可以从我的其他类中扩展这个组件。但是,由于容器包含所有的调度动作,所以我需要扩展容器,而不是组件。

【问题讨论】:

标签: javascript reactjs typescript


【解决方案1】:

我认为你可以重用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);

【讨论】:

  • 是的,我可以这样做,但我想将其用作class S extends BaseContainer。原因是因为我使用的是 Typescript,所以我需要访问 BaseContainer 的 props
猜你喜欢
  • 2022-01-22
  • 2019-09-26
  • 2013-02-27
  • 2017-06-18
  • 2019-09-18
  • 2019-05-04
  • 2019-07-11
  • 2017-04-02
相关资源
最近更新 更多