Typescript封装React展示抽象组件时State类型报错求解
问题根源
当前写法存在泛型作用域错位的核心类型问题:
- 你把
P(Props类型)、S(State类型)声明成了Presentation工厂函数本身的泛型参数 - 但实际需求里的泛型,是被继承的组件类自身可以接收的、和实例绑定的泛型,而非工厂函数调用时提前传入的参数
这导致你写Presentation<{}, StateType>(config)时,TS会把这段代码解析为“给工厂函数传递泛型实参”,但工厂返回的类本身完全没有开放向外接收P、S泛型的通道,类内部继承的React.Component<P,S>拿到的P、S永远是默认值{},自然访问this.state.width时会提示属性不存在。
正确实现方式
1. 重写工厂函数与类型定义
核心逻辑是让工厂函数返回一个支持接收泛型的类构造签名,同时把所有需要的静态元数据类型约束加在构造函数上:
import React from "react"; // 定义所有展示组件的构造函数必须满足的结构 export type PresentationConstructor = { // 类层级的静态元数据必填 title: string; description: string; date: Date; uri: string; } & { // 泛型类签名:支持实例化时传入Props、State类型,继承自React.Component new <P = {}, S = {}>(): React.Component<P, S>; }; // 内部抽象基类,不需要对外暴露 abstract class BasePresentation<P, S> extends React.Component<P, S> {} // 工厂函数:仅接收静态配置,返回带静态属性的泛型类 export function Presentation(mandatory: { title: string; description: string; date: Date; uri: string; }): PresentationConstructor { return class extends BasePresentation<unknown, unknown> { static title = mandatory.title; static description = mandatory.description; static date = mandatory.date; static uri = mandatory.uri; } as PresentationConstructor; }
2. 组件写法调整
因为现在工厂返回的是泛型类,你可以在类继承链上直接传入自己的Props、State类型,TS会自动把类型透传到组件内部:
import React from "react"; class ResizeAwarePresentation extends Presentation({ title: "My presentation's title", description: "My presentation's description", date: new Date(2021, 1, 22, 15, 30, 0), uri: "/presentation-slug" })<{}, { width: number; height: number; }> { // 此时this.state会被自动推导为{width:number, height:number},不会再报类型错误 state = { width: 0, height: 0 }; updateWindowDimensions = () => { this.setState({ width: window.innerWidth, height: window.innerHeight }); }; componentDidMount() { this.updateWindowDimensions(); window.addEventListener("resize", this.updateWindowDimensions); } componentWillUnmount() { window.removeEventListener("resize", this.updateWindowDimensions); } render() { return ( <div style={{ width: this.state.width, height: this.state.height }}> </div> ); } } export default ResizeAwarePresentation;
3. 路由自动生成的类型适配
因为我们已经用PresentationConstructor把组件构造的类型约束好了,遍历组件生成路由的逻辑可以直接获得安全类型:
import * as presentations from './presentations/index' // 将导入的组件值约束为合法的展示组件构造 const presentationClasses = Object.values(presentations) as PresentationConstructor[]; {presentationClasses.map((presentation) => ( <Route key={presentation.uri} path={presentation.uri}> {React.createElement(presentation)} </Route> ))}
关键注意点
- 泛型的位置不要错:P和S是类实例的泛型,不是工厂函数的参数,绝对不要把P、S写在
Presentation函数的泛型声明位置 - 静态属性和实例泛型完全不冲突:静态属性是挂在类构造上的固定值,和组件实例传入的Props、State类型没有关联,不会影响你遍历组件列表提取元数据生成路由
- 实现完全兼容原有简单组件写法:没有状态的普通展示组件,不需要手动传泛型,直接用默认的
{}类型就可以正常工作,和你之前的使用体验完全一致 - 代码里的类型断言是安全的:运行时返回的类本身就是React.Component的子类,完全满足构造函数的行为,断言只是在类型层面补充“支持泛型传参”的签名,不会引入运行时异常
内容的提问来源于stack exchange,提问作者user4648973
相关产品推荐
相关产品推荐

