我正在尝试在我的React项目中使用Typescript。使用HOC装饰器时出错
这将返回错误:
Test.tsx中的错误:6:1 TS1238:作为表达式调用时,无法解析类装饰器的签名。 类型'typeof WithState'不能分配给类型'typeof Test'。 类型“ typeof WithState”中缺少属性“ propTypes”。 类型'typeof WithState'中缺少属性'propTypes'。
index.ts测试:
export * from "./Test";
export * from "./TestProps";
export * from "./TestState";
TestProps:
import * as PropTypes from "prop-types";
export interface TestProps {
header: string,
count: number;
onIncrement: () => any;
}
export const TestPropTypes = {
header: PropTypes.string
};
TestState:
export interface TestState {
name: string
}
组件测试:
import React, { Component } from "react";
import {TestProps, TestPropTypes} from "./TestProps";
import {TestState} from "./TestState";
import { HOC } from "../HOC/";
@HOC
export class Test extends Component<TestProps, TestState> {
public static propTypes = TestPropTypes;
public render(): JSX.Element {
const { header } = this.props;
return <div>{header}</div>
}
}
index.ts HOC:
export * from "./HOC";
组件HOC:
import * as React from "react";
import { Subtract } from "utility-types";
interface HOCProps {
count: number;
onIncrement: () => any;
}
export const HOC = <WrappedProps extends HOCProps>(
WrappedComponent: React.ComponentType<WrappedProps>
) => {
type HocProps = Subtract<WrappedProps, HOCProps> & {
initialCount?: number;
};
interface HocState {
readonly count: number;
};
return class WithState extends React.Component<HocProps, HocState> {
public static displayName = `withState(${WrappedComponent.name})`;
public static readonly WrappedComponent = WrappedComponent;
public readonly state: HocState = {
count: Number(this.props.initialCount) || 0,
};
public handleIncrement = () => {
this.setState({ count: this.state.count + 1 });
};
public render() {
const { ...restProps } = this.props as {};
const { count } = this.state;
return (
<WrappedComponent
{...restProps}
count={count}
onIncrement={this.handleIncrement}
/>
);
}
};
};