You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为作为prop传入的React Component设置对应类型

解决方案

你传入的component为合法React组件(包含函数组件、类组件),可直接使用React内置的ComponentType类型定义,适配你当前react-router-dom v5写法的步骤如下:

  1. 导入对应类型:
import type { ComponentType } from 'react';
// 若需要严格约束组件接收的路由参数类型,可额外导入下方类型
import type { RouteComponentProps } from 'react-router-dom';
  1. 补全AppProps接口定义:
interface AppProps {
    path: string,
    isPrivate: boolean,
    // 通用写法:兼容所有可接收路由props的组件
    component: ComponentType<any>
    // 严谨写法:明确约束组件需接收路由相关props
    // component: ComponentType<RouteComponentProps>
}

你现有代码中将component重命名为首字母大写的Component的写法符合React组件渲染规范,不需要额外修改。


内容的提问来源于stack exchange,提问作者Atlante Avila

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 21:27:04