2

下面是一个例子来说明一个问题:

首先,我有一个 React 的 Typescript 定义,其中我们有一个组件的定义:

class Component<P, S> implements ComponentLifecycle<P, S> {
    static propTypes: ValidationMap<any>;
    static contextTypes: ValidationMap<any>;
    static childContextTypes: ValidationMap<any>;
    static defaultProps: Props<any>;

    constructor(props?: P, context?: any);
    setState(f: (prevState: S, props: P) => S, callback?: () => any): void;
    setState(state: S, callback?: () => any): void;
    forceUpdate(callBack?: () => any): void;
    render(): JSX.Element;
    props: P;
    state: S;
    context: {};
    refs: {
        [key: string]: Component<any, any>
    };
}

然后在应用程序中,我创建了扩展组件的类。

class App extends React.Component<any, any> {
}

我想要一个返回组件实例的函数。

function Test<T extends React.Component<any, any>>(): T
{
    return App;
}

Typescript 编译器不允许我这样做。错误是:

“typeof App”类型中缺少属性“setState”

我不明白,因为类应该从 Component 继承一切。

4

2 回答 2

4

也许你应该写

function Test<T extends React.Component<any, any>>(): T
{
    return new App();
}
于 2015-10-18T17:56:04.130 回答
0

对!这对我来说是漫长的一天。

我还是不明白。我为 react-redux 提供了 tsd,其定义如下:

export interface ClassDecorator {
    <T extends ComponentLifecycle<any, any>>(target:T): T;
}

export function connect(mapStateToProps?: MapStateToProps,
                          mapDispatchToProps?: MapDispatchToPropsFunction|MapDispatchToPropsObject,
                          mergeProps?: MergeProps,
                          options?: Options):  ClassDecorator;

在我使用它的其他文件中,我有

export default connect(
    mapStateToProps,
    mapDispatchToProps
)(App);

它正在工作。为什么我不需要通过 new App()?? 该应用程序与第一个问题相同。ComponentLifecycle 是 React.Component 实现的接口。当我在 tsd 文件中将 ComponentLifecycle 更改为 Component 时,我的代码无法编译。

于 2015-10-18T19:25:38.897 回答